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






I want it to read:






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 2


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('_'))
  • 2
    or as a simple expression for ArcGIS: '_'.join(s.zfill(4) for s in !field!.split('_'))
    – Mike T
    Commented Apr 8, 2015 at 20:10
  • 1
    Why would you need double parentheses? I tried them, and both work fine.
    – ianbroad
    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.
    – nmpeterson
    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).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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