Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I can rename layers easily enough, but I really need to replace any "_" with a " ".

This code just renames layers, but I would like to do a find and replace on each layer name

mxd = arcpy.mapping.MapDocument("current")
layers = arcpy.mapping.ListLayers(mxd)

for lyr in layers:
    if lyr.name == "X":
        lyr.name = "Y"

arcpy.RefreshTOC()
share|improve this question

closed as off-topic by Jason Scheirer, Paul, Curlew, BradHards, PolyGeo Oct 31 '13 at 21:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development are off-topic here unless they relate directly to Geographical Information Systems, but they can be asked on Stack Overflow." – Jason Scheirer, Paul, Curlew, BradHards, PolyGeo
If this question can be reworded to fit the rules in the help center, please edit the question.

3 Answers 3

It's pretty much the same code as what you have, but you just need to incorporate the Python "replace" method. By checking for the existence of the underscore in original name you can avoid needlessly updating every layer name, even if does not have an underscore.

mxd = arcpy.mapping.MapDocument("current")
layers = arcpy.mapping.ListLayers(mxd)

for lyr in layers:
    if "_" in lyr.name:
        lyr.name = lyr.name.replace("_", " ")

arcpy.RefreshTOC()
share|improve this answer

I would go for something like this:

import arcpy, os, string
mxd = arcpy.mapping.MapDocument("current")
layers = arcpy.mapping.ListLayers(mxd)

for lyr in layers:
    lyrname = str(lyr.name)
    print lyrname
    lyrname_replaced = lyrname.replace("_"," ")
    lyr.name = lyrname_replaced
    print lyrname_replaced

arcpy.RefreshTOC()
share|improve this answer
    
Perfect. Thanks for the help. –  user23498 Oct 31 '13 at 14:43
    
No problem. Ryan's code is better because he checks if "_" is in the layer name. Mine doesn't. –  Alex Tereshenkov Oct 31 '13 at 14:47

You could use the .replace operation. It should work nicely. Your code may look something like this.

mxd = arcpy.mapping.MapDocument("current")
layers = arcpy.mapping.ListLayers(mxd)

for lyr in layers:
    name = lyr.name
    name = name.replace("_", "")
    lyr.name = name

arcpy.RefreshTOC()
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.