Display number with leading zeros
Solution 1:
In Python 2 (and Python 3) you can do:
number = 1
print("%02d" % (number,))
Basically % is like printf
or sprintf
(see docs).
For Python 3.+, the same behavior can also be achieved with format
:
number = 1
print("{:02d}".format(number))
For Python 3.6+ the same behavior can be achieved with f-strings:
number = 1
print(f"{number:02d}")
Solution 2:
You can use str.zfill
:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
Solution 3:
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.
Solution 4:
print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))
prints:
01
10
100
Solution 5:
In Python >= 3.6, you can do this succinctly with the new f-strings that were introduced by using:
f'{val:02}'
which prints the variable with name val
with a fill
value of 0
and a width
of 2
.
For your specific example you can do this nicely in a loop:
a, b, c = 1, 10, 100
for val in [a, b, c]:
print(f'{val:02}')
which prints:
01
10
100
For more information on f-strings, take a look at PEP 498 where they were introduced.