views:

5181

answers:

5

Given:

a = 1

b = 10

c = 100

I want to display a leading zero for all numbers with less than 2 digits.

Essentially displaying

01

10

100

+19  A: 
x = [1, 10, 100]
for i in x:
    print '%02d' % i

results:

01
10
100

Read more information about string formatting using % in the documentation.

nosklo
The documentation example sucks. They throw mapping in with the leading zero sample, so it's hard to know which is which unless you already know how it works. Thats what brought me here, actually.
Grant
+9  A: 

Here you are:

print "%02d" % (1,)

Basically % is like printf or sprintf.

Jack M.
if you want to pass in a one-tuple use (1,). (1) ist just the value one which also works in this context.
unbeknown
You are correct. Updated. Thanks.
Jack M.
+2  A: 

Use a format string - http://docs.python.org/lib/typesseq-strings.html

For example:

python -c 'print "%(num)02d" % {"num":5}'
Airsource Ltd
+4  A: 

In Python 3.0 you would use the format() string method:

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

or using the built-in (for a single number):

print(format(i, '02d'))

See the PEP-3101 documentation for the new formatting functions.

Ber
-1: That won't work. Python's format uses curly braces, so print('{num:02d}'.format(num=i))
nosklo
fixed it. No need for a "-1" ?
Ber
Ber: aren't we supposed to vote down answers that don't work? Removed -1.
nosklo
+4  A: 

You can use zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2) 

prints:

01
10
100
Radek