I have a Python script where I'm trying to take the values from three fields (street address data - direction, street name, street type) and combine them into one field, e.g. S, Main, St should be S Main St.

I've tried three different ways, in code below, but no matter what I try the result comes out as 'SMainSt', no spaces. If the direction field, is empty, it results in ' MainSt', even when I use strip(). If the street name is two or more words, the space there is preserved, e.g. 'SHollow WoodsLn'. Any ideas on what's going wrong?

street = ('!FEDIRP!', '!FENAME!', '!FETYPE!')
val = " ".join(street)
val = "{0} {1} {2}".format("!FEDIRP!", "!FENAME!", "!FETYPE!")
val = "!FEDIRP!" + " " + "!FENAME!" + " " + "!FETYPE!"

arcpy.CalculateField_management(f, fld, val, 'PYTHON_9.3')
  • Is it script? Exclamation marks are good in field calculator.... – FelixIP Apr 12 '16 at 20:08
  • Yes, in a script. – recurvata Apr 12 '16 at 20:09
  • 1
    I guess missing quota around expression – FelixIP Apr 12 '16 at 20:14

If you want to use the Calculate Field tool (instead of an Update Cursor), what you're assigning to val needs to be an unevaluated python expression. That is, it needs to be identical to the string you would type into the Calculate Field tool if you were using the GUI version.

What you're currently assigning to val is "!FEDIRP! !FENAME! !FETYPE!".

Any of the following should work:

val = ''' " ".join([!FEDIRP!, !FENAME!, !FETYPE!]).strip() '''
val = ''' "{0} {1} {2}".format(!FEDIRP!, !FENAME!, !FETYPE!).strip() '''
val = ''' (!FEDIRP! + " " + !FENAME! + " " + !FETYPE!).strip() '''

Alternatively, you could use an Update Cursor:

with arcpy.da.UpdateCursor(f, [fld, 'FEDIRP', 'FENAME', 'FETYPE']) as c:
    for r in c:
        r[0] = " ".join(r[1:]).strip()
|improve this answer|||||
  • This almost works, It still leaves a space at the front of the string - ' Main St' instead of 'Main St' - if there's no value for FEDIRP. I use .strip() to eliminate this space, but it's not working. – recurvata Apr 14 '16 at 13:35
  • Is the .strip() inside the triple-quotes? – nmpeterson Apr 14 '16 at 13:40
  • No, like this: val = ''' "{0} {1} {2}".format(!FEDIRP!, !FENAME!, !FETYPE!) '''.strip() – recurvata Apr 14 '16 at 13:41
  • 1
    I've updated my answer with the .strip() in the appropriate places. You're making the same error as your original one: your entire expression for the calculation must be unevaluated for it to work. – nmpeterson Apr 14 '16 at 14:23
  • That did it, much appreciated! – recurvata Apr 14 '16 at 16:37

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.