Display number with leading zeros

ashchristopher picture ashchristopher · Sep 25, 2008 · Viewed 899.6k times · Source

Given:

a = 1
b = 10
c = 100

How do I display a leading zero for all numbers with less than two digits?

This is the output I'm expecting:

01
10
100

Answer

Jack M. picture Jack M. · Sep 25, 2008

In Python 2 (and Python 3) you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

print("{:02d}".format(1))

For Python 3.6+ the same behavior can be achieved with f-strings:

print(f"{1:02d}")