NYGeog

Geography, GIS, Geospatial, NYC, etc.

Tuesday, January 25, 2011

Python Field Calculator: counting characters in a string using .count()

Let's say you have a field with many items in it-say you have a shapefile of states and a field with the names of all the major rivers in that state and the river names are separated by a dash. Ex. [Nile R.-Mississippi R.-Hudson R.-Snake R.-Potomac R.-Yellow R.]

If you wanted to count the number of rivers in each state in a new field you could simply count the delimiter, the dash (-) and add 1 (because each dash separates one river from another it'll be one less dash always than the number of rivers).

Go to you field calculator, select Python and use this expression;

(!riversfieldname!.count('-'))+1

Your calculating field should be short integer in this example and should return a value of 6 in this example.