views:

83

answers:

3

So say i have

a = 5

i want to print it as a string '05'

+4  A: 

print "%02d"%a is the python 2 variant

python 3 uses a somewhat more verbose formatting system:

"{0:0=2d}".format(a)

The relevant doc link for python2 is: http://docs.python.org/library/string.html#format-specification-mini-language

For python3, it's http://docs.python.org/dev/py3k/library/string.html#string-formatting

jkerian
The new Python 3 formatting is available in 2.6 as well, 2.7/3 allows you to be a little more terse with positional arguments.
Nick T
+1  A: 
>>> print '{0}'.format('5'.zfill(2))
05

Read more here.

sukhbir
+1  A: 
a = 5
print '%02d' % a
# output: 05

The '%' operator is called string formatting operator when used with a string on the left side. '%d' is the formatting code to print out an integer number (you will get a type error if the value isn't numeric). With '%2d you can specify the length, and '%02d' can be used to set the padding character to a 0 instead of the default space.

tux21b