patternpythonCriticalCanonical
Display number with leading zeros
Viewed 0 times
withzerosdisplayleadingnumber
Problem
How do I display a leading zero for all numbers with less than two digits?
1 → 01
10 → 10
100 → 100
Solution
In Python 2 (and Python 3) you can do:
Basically % is like
For Python 3.+, the same behavior can also be achieved with
For Python 3.6+ the same behavior can be achieved with f-strings:
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}")Code Snippets
number = 1
print("%02d" % (number,))number = 1
print("{:02d}".format(number))number = 1
print(f"{number:02d}")Context
Stack Overflow Q#134934, score: 1995
Revisions (0)
No revisions yet.