How to fill with leading zeros in Python?

Question:

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 it the way above, the result is not what I expected:

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

Answer:

You can use the method that @WallaceMaxters demonstrated:

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

Another possibility is to use the zfill method of the str class, str.zfill , but for that you'll need the input to be a string, as this method simply fills strings up to the length specified in the width parameter:

>>> 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 . 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 to give you 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 think the format more elegant and powerful. You can read the full specification of the formatting language that str.format uses in the Format Specification Mini-Language .

Scroll to Top