Select to view content in your preferred language

Parse the OID field using an Update Cursor

635
2
01-24-2011 12:56 PM
ChristinaHerrick1
Emerging Contributor
I have a feature class within a geodatabase that has a field called 'cellnum' and also, by default, has an OID field.

I am trying to create an Update Cursor that will read the OID number, take the last digit, subtract it by 1, and add that value to the field 'cellnum'.  So, if the OID is 614, the cellnum value should be 3-- last digit of 614 is 4, minus 1 is 3).

I have something like this already:

sort = "C:/User/Username/Documents/project/ABE.gdb/cellanalysis_Sort1"
rows3 = arcpy.UpdateCursor(sort)
for row3 in rows3:
    fUpdate = arcpy.Describe(sort)
    num = row3.getValue("ID")
    OID = fUpdate.OIDFieldName
    value = row3.getValue(OID)
    digit = value[-1] - 1
    print "for ID:" + str(num) + " the cellnum is " + digit
del row3,rows3


However, python doesn't like my 'digit' statement.  Can anyone shed some light on this?

Thanks!
0 Kudos
2 Replies
RDHarles
Regular Contributor
Christina,
I had to convert the OBJECTID value to a string, get the last number, then convert back to integer to subtract (- 1).
There may be a "cleaner" way to do it, but this works:

import arcpy

arcpy.env.workspace = os.getcwd()

fc = "temp.gdb/Business"

# Create update cursor for feature class.
rows = arcpy.UpdateCursor(fc)
for row in rows:
    
    # Get the value from the field
    oid = row.getValue("OBJECTID")

    # Convert to string
    x = str(oid)[-1]
    # Convert to integer
    y = int(x) - 1    
    
    print y

    # Set results to field 'num'  
    row.num = y    
       
    # Execute the new value to the table
    rows.UpdateRow(row)
    
del rows
0 Kudos
NiklasNorrthon
Frequent Contributor
Cleaner way:
def last_digit_minus_1(number):
    return (number - 1) % 10
0 Kudos