# Count the number of characters in a field (Python)

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.

-

## 3 Answers

How about via the python option in the field calculator?

1. Create the count field as Integer.
2. In the field calculator -

len(!STREET_NAME!)

-
Many thanks!! len(str(!STREET!)) –  user19300 Jul 17 '13 at 19:53
It's not necessary to cast as string. OP isn't dealing with numerical values. –  Paul Jul 17 '13 at 20:02
By 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
Fixed. Thanks for the clarification. Better fire up Arc first next time... –  Jay Laura Jul 17 '13 at 20:31
@JayLaura It's just that the STREET_NAME field is already a str so it's not really needed to convert a string to a string. –  SaultDon Jul 17 '13 at 20:32
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.

-
+1 Good, simple solution –  Aaron Jul 17 '13 at 19:49

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

-
+1 for cursors. –  Paul Jul 17 '13 at 20:14
I 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