I am just learning python and I need to convert a 2 digit numeric attribute in a table to a 2 digit zero-filled attribute in a script.
For example, 9 needs to be 09.
I am just learning python and I need to convert a 2 digit numeric attribute in a table to a 2 digit zero-filled attribute in a script.
For example, 9 needs to be 09.
See the zfill() help in python.org or this stackoverflow post. As @artwork mentions, you must convert the value to string and make the calculation. You can use zfill() inside the cursor, or use as an expression in the Calculate Field tool.
n = 4
or n = 40
followed by print str(n).zfill(2)
will return the correctly padded values.
Commented
Feb 6, 2013 at 22:48
str(!NUM_ID!).zfill(2)
-- where NUM_ID is your source field.
If you already have a value and you need to make it 2 digit value, have a look:
import sys
inputValue = sys.argv[1]
checkValue = int(inputValue)
if checkValue <= 9:
inputValue = '0' + inputValue
print inputValue
input->output: 2 -> 02, 20 -> 20
zfill
or rjust
make much more sense.
This should do the trick (if using ArcGIS 10.1, for ArcGIS 10 you will have to use this update cursor):
First add a empty text field, e.g. textField to your feature class or shapefile.
You can run the below code in PythonWin, ArcMap, or ArcCatalog Python window. Or put it into a .py file and call it from a user created toolbox script tool.
Updated:
import arcpy
fc = "C://temp//Default.gdb//myLayer" # update to your layer
fields = ('numField', 'textField') # put your numeric and text field here
with arcpy.da.UpdateCursor(fc, fields) as cursor:
for row in cursor:
if row[0] <= 9:
row[1] = '0' + str(row[0])
cursor.updateRow(row)