3

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?

  • split() returns a list, this is why it is happening. Have a look at the trim() method. – Hornbydd Jan 28 '17 at 0:05
  • Actually, it's happening because of how s is defined. Just plain s = " " will work. – Paul Jan 28 '17 at 0:18
5

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)
  • Minor error, I think you meant to define field1 on the 1st line, otherwise the format function will err as undefined var. Otherwise, +1 for showing the updatecursor means of doing this. – T. Wayne Whitley Jan 28 '17 at 0:27
  • This did the trick!. – Andy Fisher Jan 30 '17 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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