1

I'm stuck on my CalculateField function with how to correctly type the syntax.

I'm not particularly tied to the variables I assigned up front.

The issue is syntax for the expression.

I am currently using ArcGIS 10.3 and Python 2.7.8.

This is the line that is getting me:

arcpy.CalculateField_management(fc, "Cohort", expression="""openYear + " to " + closeYear""")

How should I be writing the expression?

expression="'str(openYear)' + " to " + 'str(closeYear)'"

The rest is a sample of my loop statement.

#################################
for fc in fcList:
    openYear=fc[12:16]
    closeYear=fc[20:24]
    # Add "Cohort" field to *USA feature classes in scratch.mdb
    print fc
    arcpy.AddField_management(fc, "Cohort", "TEXT")
    print "Cohort added."
    # Calculate "Cohort" field to match feature class name in scratch.mdb  
    arcpy.CalculateField_management(fc, "Cohort", expression="""openYear + " to " + closeYear""")
0

1 Answer 1

5

Using the calculate field arcpy function requires the proper string input as its expression. You need to create a string that looks exactly like it would in ArcGIS's field calculator. For text fields, this means your text surrounded by double quotation marks. Something like this:

"1945 to 1965"

Translating that into a python string isn't too tough. If you want double quotes in your strings, open and close your string with single quotes.

'"1945 to 1965"'

Now to substitute the years with the variable values:

'"' + openYear + " to " + closeYear + '"'

or:

'"{0} to {1}"'.format (openYear, closeYear)

The final code:

CalculateField_management (fc, "Cohort", '"{0} to {1}"'.format (openYear, closeYear))

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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