Python program to pad zeros to a string

Python program to pad zeros to a string :

In this python programming tutorial, we will learn how to pad extra zeros to a string. For example, if the string is 2, and if we pad three zeros to this string, it will become 0002. Similarly, we can pad zeros to any type of string like 00Hello or 000world. We can pad any number of zeros to a string.

Using zfill() to a string :

In python, we can use zfill() method to pad zeros to a string. The syntax of zfill() is as below :


width is the final width of the string. This width sized string will be created after zeros are padded to the string. This method will return the final string.

Python example program :

Let’s try to implement zfill() method in python:

python zfill

Explanation :

The commented numbers in the above program denote the step number below :

1. Ask the user to enter a string. Read and store it in input_str variable.
2. Ask the user to enter the count of zeros to insert to the left of the string.
3. Find the total count, i.e. the final size of the string including the zeros.
4. Print the final zero-padded string to the user. The zfill method takes the total count of letters as an argument. For example, if you want to print 002 for the string 2, then you need to pass 3 as the argument to zfill().

Sample Output :

python zfill

python zfill

Conclusion :

We have seen how to pad zeros to the left of a string using python. Try the examples above and drop a comment below if you have any query.

Leave a Reply