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.
Syntax
str.zfill(length)
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.
Parameters
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.
# app.py h1= "MilEy CirUS" h2= "Hello Boy" h3= "Qwerty" h4= "HELLO girl" h5="lionel messi IS THE BEST" print(h1.zfill(20)) print(h2.zfill(15)) print(h3.zfill(25)) print(h4.zfill(24)) print(h5.zfill(30))
Output
➜ pyt python3 app.py 000000000MilEy CirUS 000000Hello Boy 0000000000000000000Qwerty 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.
# app.py for i in range(0,2): h=input() length=int(input()) print(h.zfill(length),"\n")
Output
Hello 6 0Hello Boy 15 000000000000Boy
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.
Conclusion
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.
- 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.
- 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.