How to Add leading Zeros to a Number in Python
Published on Aug. 22, 2023, 12:15 p.m.
To add leading zeros to a number in Python, you can use the str.zfill()
method or the f-string
syntax.
Here’s how to use str.zfill()
:
number = 7
print(str(number).zfill(2))
This will output 07
, which is the number with a leading zero.
Alternatively, you can use f-strings
to format the number with leading zeros:
number = 7
print(f"{number:02}")
This will also output 07
.
Note that both methods return a string, not an integer. If you need to use the integer value later, you can convert the string back to an integer using the int()
function.