W3docs

How do I pad a string with zeroes?

You can use the zfill() method to pad a string with zeros on the left side.

You can use the zfill() method to pad a string with zeros on the left side. For example:

Pad a string with zeroes in Python using the zfill method

s = "123"
s = s.zfill(5)
print(s)

This will add two zeros on the left side of the string s, so that the resulting string has a total length of 5.

You can also use the format() function to pad a string with zeros. For example:

Pad a string with zeroes in Python using the format method

s = "123"
s = "{:05d}".format(int(s))
print(s)

This will also add two zeros on the left side of the string s, so that the resulting string has a total length of 5. The 05 in the format string specifies the total width of the output string, including the padding. The d specifies that the value being formatted is a decimal integer.

You can also use the rjust() method to pad a string with zeros on the left side. For example:

Pad a string with zeroes in Python using the rjust method

s = "123"
s = s.rjust(5, '0')
print(s)

This will add two zeros on the left side of the string s, so that the resulting string has a total length of 5. The first argument to rjust() is the total width of the output string, including the padding, and the second argument is the padding character. This method is typically used to right-align strings.