by @saigowthamr

How to add leading zeros to a Python String

Home » python » How to add leading zeros to a Python String

To add 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.

num = "7"

print (num.rjust(4, '0'))

Output:

0007