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.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →