HOW TO
In ArcGIS Pro, the Python len() function can be used in field calculations to count and return the number of characters in a text field. For example, the function can be used in expressions to populate a field with values based on the character count of cells in another field, which can be useful when working with standardized codes or acronyms.
The image below shows the 'Category' field containing acronyms in a feature's attribute table in ArcGIS Pro. In this article, a new field is populated with additional characters if the values in the ‘Category’ field have three or two characters instead of four.
Note: The workflow in this article can only be applied to fields with the text data type, as the len() function is used to count the characters in a string.
calculate_field(!<fieldName>!)
def calculate_field(<field>): if (len(<field>) == <characters>): return ("<value>" + <field>) else: return (<field>)
def calculate_field(<field>): if (len(<field>) == <characters>): return ("<value>" + <field>) elif (len(<field>) == <characters>): return ("<value>" + <field>) else: return (<field>)
Note: The if…elif..else statement is used to include more than a single number of characters from the input field to be counted.
The code block below shows the full working expression using the if…else statement.
def calculate_field(cat): if (len(cat) == 3): return ("A" + cat) else: return (cat)
The code block below shows the full working expression using the if…elif…else statement.
def calculate_field(cat): if (len(cat) == 3): return ("A" + cat) elif (len(cat) == 2): return ("AA" + cat) else: return (cat)
The image below shows the ‘Code’ field populated with the additional characters ‘A’ or ‘AA’ if the ‘Category’ field values have three or two characters instead of four.
Get help from ArcGIS experts
Download the Esri Support App