python – Display number with leading zeros
python – Display number with leading zeros
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})
You can use str.zfill
:
print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))
prints:
01
10
100
python – Display number with leading zeros
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.