Display numbers with leading zeros in Python

01
10
100

In Python 2 you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf.

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

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

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

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

References
https://stackoverflow.com/questions/134934/display-number-with-leading-zeros

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.