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:
So, you can use this in your expression:
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.