# Zero filling attributes using ArcPy/Python?

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.

• If your field is numeric field you will have to create a new text field to do this. Also, what version of ArcGIS are you using? – artwork21 Feb 6 '13 at 15:36
• Thanks I am using 10.0 and the zfill worked for me. I'm an old dog learning new tricks much apprecaited. – Giuseppe Filoso Feb 13 '13 at 14:29

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.

• Good suggestion! `n = 4` or `n = 40` followed by `print str(n).zfill(2)` will return the correctly padded values. – RyanKDalton Feb 6 '13 at 22:48
• Here is the syntax to use in a Calculate Field expression: `str(!NUM_ID!).zfill(2)` -- where NUM_ID is your source field. – blah238 Feb 7 '13 at 12:18

If you already have a value and you need to make it 2 digit value, have a look:

``````import sys

inputValue = sys.argv
checkValue = int(inputValue)

if checkValue <= 9:
inputValue = '0' + inputValue
print inputValue
``````

input->output: 2 -> 02, 20 -> 20

• While this will work, the built-in functions `zfill` or `rjust` make much more sense. – blah238 Feb 7 '13 at 6:44

This should do the trick (if using ArcGIS 10.1, for ArcGIS 10 you will have to use this update cursor):

1. First add a empty text field, e.g. textField to your feature class or shapefile.

2. 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 <= 9:
row = '0' + str(row)
cursor.updateRow(row)
``````
• I don't think this will work if the number is already 2 digits (10 - 99)? I think you will end up with a padded '010' or '099' when the user actually wants '10' and '99' if the number is already 2 digits long? – RyanKDalton Feb 6 '13 at 22:44
• Updated my answer, thx. – artwork21 Feb 7 '13 at 11:36