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 .