Display number with leading zeros Display number with leading zeros python python

Display number with leading zeros

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:


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


You can use str.zfill:




In Python 2.6+ and 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.