HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Display number with leading zeros

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
displaynumberleadingzeroswith

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:

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.