[GIS] Using .len() in IF THEN statement in ArcMap field calculator

arcgis-desktoparcmapfield-calculatorpythonstring

I have a string field with values of varying lengths (1-4). I need each value to have a length of 5 characters by adding zeros to the value until the length equals 5. For example:

123

needs to be:

00123

I am writing a Python function in ArcMap's Field Calculator but it is incorrect. This is my code:

def zeros(photoLen):
  if photoLen == 4:
    return "0"
  elif photoLen == 3:
    return "00"
  elif photoLen == 2:
    return "000"
  elif photoLen == 1:
    return "0000"
  else:
    return 0

And then I call the function like this:

zeros(!photoStr!)

What do I need to change so this function will work?

Best Answer

In addition to @DWynne's answer, I'll add that there is a built-in python function that does exactly this (located a little bit further down the page on DWynne's link). It's called zfill and according to the documentation:

Returns the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than or equal to len(s).

So, you can use this in your expression:

!photoStr!.zfill(5)

It's no better than using rjust, but it's a bit shorter. I use it all the time when I want to pad a string with zeroes.