Getting ArcGIS to include leading zeros in text field?

Python has a built-in for leading zeros. Use str.zfill() to add leading zeros into a text field.

my_string = "1"
print my_string.zfill(2)   # Prints 01

my_string = "1000"
print my_string.zfill(2)   # Prints 1000

(example from https://stackoverflow.com/a/21620624/5754917)

So in the field calculator you just need to specify the name of the field with your ID and then fill with zeros

str(!myfield!).zfill(5)

enter image description here

And the end result:

enter image description here

Remember to switch the field calculator to "Python Parser"


Just put your text in quotes. Double quotes if you are in VB Script mode, and double or single if in Python mode.

To explain: When you just enter the numbers, you are giving Field Calculator a value in integer form, which it will convert to a string for you in order to enter it into the string type field. For integers, the leading zeros have no value and no meaning, so they are omitted. If you put it in quotes, you are instead passing it a string, which is already the correct data type, so it gets left alone.

This also assumes that this field is actually of type "Text". Maybe it was set to Long or Short Integer, that would also cause this behavior.


You can use a Python code block.

Add this function definition in code block:

def addZero(value):
    if value <= 9:
        output = '0000' + str(value)
    elif value <= 99:
        output = '000' + str(value)
    elif value <= 999:
        output = '00' + str(value)
    elif value <= 9999:
        output = '0' + str(value)
    return output

You can use it as:

addZero(!Field!) # numeric field

or

addZero(123) # for example