Python String zfill: The Complete Guide

Python zfill() method fills the string at left with 0 digits to make a string of length width. It returns a string containing a sign prefix + or – before the 0 digits. It returns the original length string if the width is less than the string length.

Python String zfill()

Python zfill() is a built-in string function used to append zero to the left side of the given string. It is a padding mechanism. The number of 0’s to be appended decided by the argument, a number passed in the zfill() method.

The argument is the total length of the list. Suppose the current length of the string is 20, and the argument is 30, then the zfill() method will attach 10 zeroes to the leftmost side of the string to make that string of length 30. The zfill() function returns a string.



Here str is the string variable that holds the main string, which must be filled.

Length is the length of the string that we want to make.


It takes a single parameter, which is the length. It specifies the length of the string we want. It must be greater than the current length of the string.

Return Value

It returns a string with the required number of zeroes padded in the main string.

Example program on zfill() in python

Write a program to show the working of the zfill() method in python.


h1= "MilEy CirUS"
h2= "Hello Boy"
h3= "Qwerty"
h4= "HELLO girl"
h5="lionel messi IS THE BEST"



➜  pyt python3
000000000MilEy CirUS
000000Hello Boy
00000000000000HELLO girl
000000lionel messi IS THE BEST
➜  pyt

Example 2: Write a program to take user input and then use the zfill method in python.


for i in range(0,2):




It fills the string with zeros until it is 10 characters long.

Python zfill() method adds zeros (0) at the beginning of a string until it reaches a particular length.

If a value of the len parameter is less than the length of a string, no filling is done.


Python zfill() returns the copy of a string with ‘0’ filled to the left. The length of the returned string depends on the width provided in the arguments.

  1. Let’s say the initial length of the string is 10. And, the width is specified 15. In this case, the string zfill() returns a copy of the string with five ‘0’ digits filled to the left.
  2. Let’s say the initial length of the string is 10. And, the width is specified 8. In this case, the string zfill() doesn’t fill ‘0’ digits to the left and returns the copy of an original string. So, the length of the returned string, in this case, will be 10.

See also

Python string split()

Python string splitlines()

Python string trim()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.