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.
Not to be a troll, but I am @Wallacemaxters :) (what you asked and what you answered)
– Wallace Maxters