Problem
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 result I’m looking for:
01
10
100
Asked by ashchristopher
Solution #1
You can accomplish the following in Python 2 (and Python 3):
number = 1
print("%02d" % (number,))
In a nutshell, percent is similar to printf or sprintf (see docs).
The same behavior can be done with format: in Python 3.+.
number = 1
print("{:02d}".format(number))
The similar effect may be done with f-strings in Python 3.6+:
number = 1
print(f"{number:02d}")
Answered by Jack M.
Solution #2
You can use str.zfill to fill in the blanks:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
Answered by Datageek
Solution #3
You’d use the format() string function in Python 2.6 and 3.0+:
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'))
The new formatting functions are documented in -3101.
Answered by Ber
Solution #4
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
prints:
01
10
100
Answered by Kresimir
Solution #5
Using the new f-strings introduced in Python >= 3.6, you may perform this quickly by using:
f'{val:02}'
which prints the variable with name val with a fill value of 0 and a width of 2.
You can perform this in a loop for your unique example:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
which prints:
01
10
100
Take a look at PEP 498, where f-strings were first introduced, for more information.
Answered by Dimitris Fasarakis Hilliard
Post is based on https://stackoverflow.com/questions/134934/display-number-with-leading-zeros