How to fill left zeros in Python?

Asked

Viewed 12,860 times

5

In php, I know we can fill a number with zeros through the printf

Example:

printf('%04s', 4); // Imprime: "0004"

How could I do that in Python?

When I try to do it the way above, the result is not as expected:

print '%04s' % 4; #Imprime: \t\t\t\t4

3 answers

8


You can use the method @Wallacemaxters demonstrated:

>>> print '%05d' % 4
'00004'

Another possibility is to use the method zfill class str, the str.zfill, but for this you will need the input to be a string, as this method simply completes strings up to the size specified in the parameter width:

>>> print '4'.zfill(5)
'00004'
>>> print str(4).zfill(5)
'00004'
>>> print 'xpto'.zfill(5)
0xpto

Or finally use the format method of the str class, the str format.. See some examples:

>>> print '{:0>5}'.format(4)
'00004'
>>> print '{:0<5}'.format(4)
'40000'
>>> print '{:0^5}'.format(4)
'00400'

A more complete example for you to have an idea of what the format can do:

>>> pessoa = {"nome": "Fernando", "usuario": "fgmacedo"}
>>> print '<a href="{p[usuario]}/">{p[nome]} ({0} pontos)</a>'.format(4, p=pessoa)
<a href="fgmacedo/">Fernando (4 pontos)</a>

I think the format more elegant and powerful. You can read the complete specification of the formatting language that the str.format uses in Format Specification Mini-language.

  • 1

    Not to be a troll, but I am @Wallacemaxters :) (what you asked and what you answered)

4

To do this in Python, it is necessary to use the formatting argument d.

Behold:

print '%04d' % 4 #Imprime: 0004

% - is the modifier

0 - is the value that will be used in the fill

4 - is the quantity used to fill in a certain value declared before it (in this case 0).

Therefore, if we wanted to fill in 8 zeros, we would:

print '08%d' % 4; #Imprime: 00000008

1

Using f-strings (literal strings) the documentation of which is here and here, we can use the following code:

a = 4
print(f'{a:04}')

Running this code we will receive the following output:

0004

Then the numerical values will have the number of digits - which in this case is 4 - completed with zeros on the left.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.