2

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.AddField_management(inputFeatureClass,"CountChr","SHORT")
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)
    arcpy.AddField_management(inputFeatureClass,"CountChr","SHORT")

    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 ?

6
  • Is your input field a text field and your count field a numeric field? Commented Sep 25, 2015 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) Commented Sep 25, 2015 at 20:23
  • What's the field type for the field "Countchr"? Commented Sep 25, 2015 at 20:24
  • Wrong spatial extent could be a reason for weird fc behavior
    – FelixIP
    Commented Sep 25, 2015 at 21:09
  • 1
    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)? Commented Sep 26, 2015 at 12:15

2 Answers 2

3

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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