How to use python string method zfill()

Python Faysal Shuvo

Python String zfill() Method:

In python, to add zero (0) at the beginning of the string we use zfill() method. This zfill() method returns the string with zero (0) padded left to string which is a copy of that string. It takes a number as a parameter it adds zero (0) at the beginning of the string until the given number is equal to the length of the string. And if the given value of the parameter is less than the length of the string then there will be no zero (0) padded to the left. It will return the same string. 

If the string has a "+" or "-" sign then the zero (0) will be padded after the  "+" or "-" sign.


Syntex: 

str.zfill(width)

width(required): This is the length of the returned string with zero (0) padded to the left of the string.


1. Width is greater than the string length:

Let's use a value that is greater than the string length. It will return a copy of the string with zero (0) padded to its left and the total length is equal to the width.

str1 = "python"
str2 = str1.zfill(10) 
print(str2)

OUTPUT: 

0000python


2. Width is less than or similar to the string length:

Now let's use a value that is less than or similar to the string length. It will not add any zero in front of the given string. The return value will remain the same.

str1 = "python"
str2 = str1.zfill(5) 
print(str2)

OUTPUT:

python


3. String with "+" or "-" sign 

So, if the value is less or similar then the value will be the same. But if the value is greater than the padded zero (0) will be added after the "+" or "-" sign.

str1 = "-python"
str2 = str1.zfill(10) 
print(str2)

OUTPUT:

-000python


4. Use zfill() in number: 

To use zfill() method in number first you have to convert the number to a string. After that, you can use zfill() to your converted value.

num = 123
str1 = str(num)
str2 = str1.zfill(5) 
print(str2)

OUTPUT:

00123



Hope this how to use python string method zfill() article helps you understand the zfill() method. If you have any feedback you can comment below.