Select to view content in your preferred language

Python, ArcGIS and Weird String Error

2162
2
03-29-2013 12:40 PM
BradOleson
Emerging Contributor
I have a FC that I am working with in Python.  I add a text field to it and want to calculate the field values based on a string variable.  The string is read in and parsed to get the value.  Example: Python reads in "1603-01_mp2.0", splits the string at the underscore, and uses the first item in the split: 1603-01.  So, line = 1603-01.

Then, to make it even MORE of a string, I do lineName = "Line"+line.  This results in "Line1603-01".  I know this to be good, because I have used print lineName to check.

Fast forward to where I try to calculate the value of the text field in the FC.  I use this python line:
arcpy.CalculateField_management(TempPLCL_Point, "Route", lineName, "PYTHON", "")

During this calculation, though, it appears that either ArcGIS or Python wants to treat the - as a minus sign and do math on the string.  I get the following error:
ExecuteError: ERROR 000539: Error running expression: Line1603-01 <type 'exceptions.NameError'>: name 'Line1603' is not defined
Failed to execute (CalculateField).

How can I get past this seemingly simple problem that shouldn't be a problem at all?
Tags (2)
0 Kudos
2 Replies
JoelCalhoun
Deactivated User
It would be nice to see the whole code snippet but I think I see what your problem is.

Your code:
arcpy.CalculateField_management(TempPLCL_Point, "Route", lineName, "PYTHON", "")

ArcGIS Help 10.1:
arcpy.CalculateField_management (in_table, field, expression, {expression_type}, {code_block})

I do lineName = "Line"+line
I have made bold the problem.  It seems that you are trying to pass in a string variable that equals the result of your expression instead of the expression itself.

Try this: (Note: This would be if you were using a shapefile and MP_VAL was the field you were pulling the 1603-01_mp2.0 value from.)
lineName = '"Line" + !MP_VAL!.split("_")[0]'
arcpy.CalculateField_management(TempPLCL_Point, "Route", lineName, "PYTHON", "")

Joel
0 Kudos
BradOleson
Emerging Contributor
That pointed me in the right direction.  I ended up with:
lineName = "'Line" + line + "'";

Thanks!

Brad
0 Kudos