How to fill in the leading zeros in Python?

4

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

Example:

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

How could I do this in Python ?

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

print '%04s' % 4; #Imprime: \t\t\t\t4
    
asked by anonymous 13.08.2015 / 21:39

2 answers

6

You can use the method that @WallaceMaxters demonstrated:

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

Another possibility is to use the zfill method of the str class, 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 width :

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

Or finally use the formatting method of the str class, str.format . Here are 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 get an idea of what 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 find format more elegant and powerful. You can read the full specification of the formatting language that str.format uses in Format Specification Mini-Language .

    
14.08.2015 / 15:37
3

To do this in Python , you must use the format argument d .

See:

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

% - is the

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

4 - is the amount used to fill with a certain value, previously declared to it (in this case 0).

So if we wanted to fill with 8 zeros, we would do:

print '08%d' % 4; #Imprime: 00000008
    
13.08.2015 / 21:39