Display number with leading zeros


Question

Given:

a = 1
b = 10
c = 100

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

That is,

01
10
100
1
785
6/22/2018 8:51:49 PM

Accepted Answer

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}")
862
12/18/2018 4:04:49 PM

You can use str.zfill:

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

prints:

01
10
100

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon