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

3 Answers3

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()
RyanKDalton
  • 23,068
  • 17
  • 110
  • 178
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()
Alex Tereshenkov
  • 29,912
  • 4
  • 54
  • 119
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()
Barbarossa
  • 5,797
  • 27
  • 61