Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 4 down vote accepted

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!)

share|improve this answer
1  
Many thanks!! len(str(!STREET!)) –  user19300 Jul 17 '13 at 19:53
1  
It's not necessary to cast as string. OP isn't dealing with numerical values. –  Paul Jul 17 '13 at 20:02
1  
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
1  
Fixed. 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 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.

share|improve this answer
    
+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
share|improve this answer
2  
+1 for cursors. –  Paul Jul 17 '13 at 20:14
1  
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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