I have a number of four or fewer digits, e.g. 8
or 12
or 197
. I'd like to put 0's in front of this number until it is 4 digits long, e.g. 0008
or 0012
or 0197
. What would be the easiest way to go about this in Python? What would be the most "Pythonic"?
I could do a series of if statements, like so:
if len(number) == 1:
number = '000' + number
...
But I have a feeling there is a more elegant way.
Let's look at an example in Excel. Here we have the number 90 with no leading zeros. To add a zero, click into the cell and in front of the number press your Apostrophe key (') and add as many zeros as you want. For this example, one zero will be added.
Several Pythonic ways to do this, I am really liking the new f-strings as of Python 3.6:
>>> f'{5:04}'
'0005'
This uses the string formatting minilanguage:
>>> five = 5
>>> f'{five:04}'
'0005'
The first zero means the fill, the 4 means to which width:
>>> minimum_width = 4
>>> filler = "0" # could also be just 0
>>> f'{five:{filler}{minimum_width}}'
'0005'
Next using the builtin format function:
>>> format(5, "04")
'0005'
>>> format(55, "04")
'0055'
>>> format(355, "04")
'0355'
Also, the string format method with the minilanguage:
>>> '{0:04}'.format(5)
'0005'
Again, the specification comes after the :, and the 0 means fill with zeros and the 4 means a width of four.
Finally, the str.zfill method is custom made for this, and probably the fastest way to do it:
>>> str(5).zfill(4)
'0005'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With