2

I have a text field, field1, that's populated with 14-digit identifiers, like "01234567890123".

I create a new field, field2, that I want to show the first four digits of field1.

I would like to do this using arcpy.

4

kind of figured it out as soon as I posted. Figured I should post the answer...

arcpy.CalculateField_management(myFeatureLayer, field2, "!field1![0:4]", "PYTHON")

suppose I should add that one can apply any standard Python string functions to !field1! and that this syntax can be used in the Field Calculator if one toggles the Python radio button to the on position.

  • 4
    As in Aarons' answer !field1![0:4] the 0 is not needed in 0:4, so if you say !field1![:4] python knows you want to start at 0; likewise string[4:] goes to the end, string[:-2] is the string shortened by 2 characters, this is very handy if you want to use FileName[:-4] to remove extensions: abc.txt -> abc, abcdefgh.txt -> abcdefgh without having to know how long the string is... handy! – Michael Stimson Jul 2 '15 at 2:25
1

Here is an Update Cursor approach:

import arcpy

shp = r'C:\path\to\your\shapefile.shp'

with arcpy.da.UpdateCursor(shp, ["field1", "field2"]) as cursor:
    for row in cursor:
        row[1] = row[0][:4]
        cursor.updateRow(row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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