Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put zeros in front of a number to make it 4 digits [duplicate]

Tags:

python

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.

like image 954
Ben Caine Avatar asked Jun 09 '14 20:06

Ben Caine


People also ask

How do you have a zero in front of a number Excel?

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.


1 Answers

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'
like image 116
Russia Must Remove Putin Avatar answered Oct 24 '22 07:10

Russia Must Remove Putin