[GIS] Removing white space from field using field calculator

arcgis-10.4arcgis-desktopfield-calculatorpython-parser

I am trying to remove extra spaces from values in a field programatically using a python script. This is the script I'm using:

field1 = "FULLST_NAME"
calc1 = "s.join(!" + field1 + "!.split())"
s = "\' \'"
arcpy.CalculateField_management(c_lines, field1, calc1, "PYTHON_9.3")

The expression used in calc1 works fine when I manually input it in the field calculator, i.e.

"   S STATE    ROUTE " is changed to "S STATE ROUTE"

However, when executing the script, it outputs:

"S' 'STATE' 'ROUTE"

with the ' ' between each string. I'm guessing there is some syntax I'm missing when storing the calculation in the variable and using it as a parameter in CalculateField_management(). How can I fix this?

Best Answer

When writing expressions for field calculator that perform string operations, I find it simpler to use triple-quoted strings. It can be tricky to escape otherwise (or, as you tried, you need to use variable substitution, which is strange).

field1 = "FULLST_NAME"
calc1 = """
' '.join(!{}!.split())
""".format(field1)

arcpy.CalculateField_management(c_line, field1, calc1, "PYTHON_9.3")

This is a fairly simple operation, but once you start using code blocks, cursors really shine:

with arcpy.da.UpdateCursor(c_line, field1) as cursor:
    for row in cursor:
        row[0] = " ".join(row[0].split())
        cursor.updateRow(row)
Related Question