# How to add "0" to multiple parts of text value in Field Calculator with Python

I have values in a text column that are as follows:

``````000_100

100_200

...

1000_1100

1100_1200
``````

I want it to read:

``````0000_0100

0100_0200

...

1000_1100

1100_1200
``````

I want all values to have the same number of characters, for example 9. The numbers in the hundreds separated by the "_" need a "0" infront for this to be accomplished. I saw that I can use zfill to add a "0" to the beginning, but is there a way to specify where to put a second "0"?

## 2 Answers

The `zfill` string method, along with some basic string splitting/joining, will let you do this very slickly:

``````def update_text(old_text):
new_text_parts = [num.zfill(4) for num in old_text.split('_')]
new_text = '_'.join(new_text_parts)
return new_text
``````

If you would prefer not to bother with a function in the Field Calculator code block, you can simplify this (as Mike T commented) to a single expression:

``````'_'.join(num.zfill(4) for num in !field!.split('_'))
``````
• or as a simple expression for ArcGIS: `'_'.join(s.zfill(4) for s in !field!.split('_'))` Commented Apr 8, 2015 at 20:10
• Why would you need double parentheses? I tried them, and both work fine. Commented Apr 8, 2015 at 20:56
• Hmm, I could swear I've received errors before without explicitly using a generator or list in `join`. Must have been another method I was thinking of. Commented Apr 8, 2015 at 23:05

If you are using Field Calculator, you can create a new field of text type and calculate the field to be:

``````def updateValue(textField):
newval = textField.split('_')
if len(newval[0]) == 3:
newval[0] = '0' + newval[0]
if len(newval[1]) == 3:
newval[1] = '0' + newval[1]
total_val = newval[0] + '_' + newval[1]
return total_val
``````

Remember to use the Advanced block as outlined in the Calculate Field examples (look at the Using code blocks section).

``````updateValue(!your_text_field!)
``````