5

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()

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.

10

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()
4

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()
  • 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
1

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()

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