How to add leading zeros to a Python String
Learn, how to add leading zeros in a string in Python with the help of examples.
Using the zfill() method
To add the leading zeros to a python string, we can use the zfill()
method.
Here is an example, that adds zeros to the left side of a numeric string 5
.
num = "5"
print (num.zfill(4))
Output:
0005
Similarly, you can also use the rjust()
method to add the leading zeros.
num = "7"
print (num.rjust(4, '0'))
Output:
0007