How do I pad a string with zeroes in Python?

Better Stack Team
Updated on February 3, 2023

You can pad a string with zeros in Python by using the zfill() method. This method adds zeros to the left of the string until it reaches the specified length.

Here's an example:

 
s = '123'
padded = s.zfill(5)
print(padded) # 00123

In this example, the string s is padded with two zeros on the left to reach a length of 5.