views:

88

answers:

6

Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits = 5 giving me: '00123'.

If I wanted to display it in 6 digits I would have digits = 6 giving: '000123'.

How would I do this in Python?

+7  A: 

There is a string method called zfill:

>>> '12344'.zfill(10)
0000012344

It will pad the left side of the string with zeros to make the string length N (10 in this case).

orangeoctopus
This is exactly what I'm looking for, I just do '123'.zfill(m) which allows me to use a variable instead of having a predetermined number of digits. Thanks!
Eddy
+1  A: 
'%0*d' % (5, 123)
Ignacio Vazquez-Abrams
This is also quite useful for more general cases. This is the old style of formatting isn't it? It's a shame that the old style is being phased out
Eddy
+3  A: 
print "%03d" % (43)

Prints

043

st0le
A: 

Use string formatting

print '%(#)03d' % {'#': 2}
002
print '%(#)06d' % {'#': 123}
000123

More info here: link text

Blue Peppers
+5  A: 

If you are using it in a formatted string with the format() method which is preferred over the older style ''% formatting

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'

See
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings

Here is an example with variable width

>>> '{num:0{width}}'.format(num=123, width=6)
'000123'

You can even specify the fill char as a variable

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
gnibbler
+1 for mentioning the new format method. It's taking a bit to get used to, but I actually feel it's a bit cleaner than the old `%` style, which feels ironic to me because I used to feel that the `%` style was the cleanest method.
Wayne Werner
How do you set a variable number of zeroes? I mean, say I wanted m digits, {0:0m} doesn't work.
Eddy
The new format does not make it easy to have a variable width.
Ignacio Vazquez-Abrams
@Eddy, to have variable width you'd need to use format twice, I added an example to my answer, but it's not pretty
gnibbler
`"{{0:0{m}}".format(m=3).format(9)` => `'009'` Seems pretty easy to me?
Wayne Werner
@Eddy, Wayne Werner, I found a better way to have the variable width
gnibbler
Why yes, gnibbler, yes you did. Too bad I can only upvote once ;)
Wayne Werner
A: 
count=5
num='123'
'0'*(count-len(num))+num
wizztjh
some people just hate 'asd'*5but this is how it come in handy
wizztjh