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?
-
You're passing a string so if len(photoLen)==4: is more correct, if photoLen == 4: will give a 'type mismatch' error comparing a string with a number and then return "0" + photoLen... but still, the answer by DWyne is how to right justify with a set number of 0's.Michael Stimson– Michael Stimson2015年06月24日 01:10:55 +00:00Commented Jun 24, 2015 at 1:10
4 Answers 4
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.
Actually, you could do this without a function. Try using str.rjust. An expression of !photoStr!.rjust(5, '0')
will return a string with padded 0's to the left of your number string.
- '1' becomes '00001'
- '12' becomes '00012'
- '123' becomes '00123'
- '1234' becomes '01234'
Python's builtin string formatting will do what you want:
'{0:0>5d}'.format(photoStr)
The 0 before the : means first argument (photoStr), the next 0 is the fill character,> means right-aligned, 5 is the length of the formatted string, then d means a decimal number.
For example:
>>> '{0:0>5d}'.format(123)
'00123'
>>> '{0:0>5d}'.format(13)
'00013'
>>> '{0:0>5d}'.format(1)
'00001'
These are great string functions that I didn't know about. Just for good measure, I'll add a method I've used in the past:
expression:
zeros(!photoStr!)
code block:
def zeros(value):
desired_len = 5
return (desired_len-len(value))*"0"+value
-
1You could add the
desired_len
as a parameter to the function. Likedef zeros(value, desired_len):
. That way, you can change the length as required. Then, you call it likezeros(!photoStr!, 5)
orzeros(!photoStr!, 8)
etc.Fezter– Fezter2015年06月24日 05:16:00 +00:00Commented Jun 24, 2015 at 5:16
Explore related questions
See similar questions with these tags.