# Counting characters in ArcPy script?

can somebody tell me how can i count character in a field either using field calculator or cursor.

i tried the below code :

import arcpy

inputFeatureClass = arcpy.GetParameterAsText(0)
InputField = arcpy.GetParameterAsText(1)
expression = "len(!" + InputField + "!)"

arcpy.CalculateField_management(inputFeatureClass,"CountChr",expression,"PYTHON_9.3")


but result is null.

i tried cursor :

import arcpy

#taking input from user

inputFeatureClass = arcpy.GetParameterAsText(0)
InputField = arcpy.GetParameterAsText(1)

cursor = arcpy.da.UpdateCursor (inputFeatureClass, [InputField, "CountChr"])
for row in cursor:
row[1] = len(row[0])
cursor.updateRow(row)
del cursor


but result is again null

can somebody tell me why this is happening ?

• Is your input field a text field and your count field a numeric field? – Emil Brundage Sep 25 '15 at 20:04
• Yes InputField is a text field, and i am adding a a new field name "Countchr" and counting characters in it from InputField(see code) – Akhil Kumar Sep 25 '15 at 20:23
• What's the field type for the field "Countchr"? – Emil Brundage Sep 25 '15 at 20:24
• Wrong spatial extent could be a reason for weird fc behavior – FelixIP Sep 25 '15 at 21:09
• perhaps wrongly, but i often start throwing in print() statements to debug - what do you get if you print row[0] to the screen (or write to a file if there are too many rows to print to screen)? – fluidmotion Sep 26 '15 at 12:15

If you have some values that are null, that may be causing the issue. Try using the following codeblock in the field calculator:

def length(field):
return len(field) if field else 0


and

CountChr = length(!yourFieldName!)


You need to pass the field name behind the input field parameter before converting the expression variable to a string. Otherwise the field name passed to calculate field will simply be "len (!InputField!) instead of the actual field name for that parameter. Try changing

expression = "len(!" + InputField + "!)"


to

expression = "len(!{0}!)".format(InputField)