10

I am entering characters in a text field that is essentially a 5 number "ID". I need leading zeros to be included in the value, but every time I enter or calculate the field, the leading zeros are removed(even though the field properties say it is a 5 character text field).

How do I force the field to include leading zeros?

4 Answers 4

14

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"

0
3

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.

2
  • Thanks, I guess this will work, too. But I will eventually need to grab the value without the leading zeros from part of another field as part of a larger semi-automatic process.
    – CJSF
    Commented Aug 10, 2017 at 21:52
  • If you can edit your question and add some more details and the entire code you currently have, we could probably help you better. It sounded like you were just manually writing values to a bunch of rows. Commented Aug 11, 2017 at 1:05
2

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
0
2

As mentionned in the other answers, you need to make sure your numbers are converted into strings.

If you lose your 0's or have them in a numerical field, create a string column width 5, just type in the following Python command :

str(!MYFIELD!).zfill(5)
0

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