Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
    
split() returns a list, this is why it is happening. Have a look at the trim() method. – Hornbydd 7 hours ago
    
Actually, it's happening because of how s is defined. Just plain s = " " will work. – Paul 7 hours ago

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)
share|improve this answer
    
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 7 hours ago
    
@T.WayneWhitley thanks for catching that. – Paul 7 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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