Python String Zfill() Method Example

  3 weeks ago     Views:  107  


Python zfill() is an inbuilt python string method that is 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, which is 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.

Python String zfill()

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

Syntax

str.zfill(length)

Here str is the string variable that holds the main string, which is to 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

Hope you like this small article.


Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

OR

No Comments