I have a field that contains street names and a second field called COUNT. I need to perform a Python field calculation on the COUNT field that counts the number of characters in the STREET_NAME field. For example if the street name is Main St then the COUNT field would be 7.
How about via the python option in the field calculator?
- Create the count field as Integer.
In the field calculator -
len(!STREET_NAME!)
-
@user19300 No problem. If one of the answers has worked for you, be sure to check it as answered. – Jay Laura Jul 17 '13 at 19:56
-
1It's not necessary to cast as string. OP isn't dealing with numerical values. – Paul Jul 17 '13 at 20:02
-
1By using single quotes around the field name you then present the
STREET_NAME
as the string, so all your counts get the same value: 11 or so in this case. – SaultDon Jul 17 '13 at 20:30 -
1Fixed. Thanks for the clarification. Better fire up Arc first next time... – Jay Laura Jul 17 '13 at 20:31
-
1@JayLaura It's just that the
STREET_NAME
field is already astr
so it's not really needed to convert a string to a string. – SaultDon Jul 17 '13 at 20:32
And to round things out with a cursor example...
import arcpy
# Create update cursor for feature class
rows = arcpy.UpdateCursor(r"C:\path\to\your\featureclass")
for row in rows:
row.COUNT = len(row.STREET_NAME)
rows.updateRow(row)
# Delete cursor and row objects to remove locks on the data
del row
del rows
-
1I thought deleting rows and cursors was unnecessary now. Can't you just do "with arcpy.UpdateCursor(...) as rows:"? – sgillies Jul 17 '13 at 21:49
-
I'm not sure if the "normal" search cursor supports with statements. At least, I can't get it to work on my end. Then again, I'm not terribly familiar with normal cursors anymore now that there is the data access module. – Paul Jul 17 '13 at 22:10
arcpy.CalculateField_management("<file>", "COUNT", "len(!STREET_NAME!)", "PYTHON_9.3")
or
arcpy.CalculateField_management("<file>", "COUNT", "len([STREET_NAME])", "VB")
Since you are dealing with street names, I'm assuming that the field is already a string.