Python String zfill() Method
In this tutorial, we will learn zfill() method in Python with some examples.
zfill() means “Zero Fill”. The string zfill() method of Python returns a copy of the string with ‘0’ characters padded to the left of the string. It simply means that it will add no. of zero’s in your string with a defined width.
Syntax :
str.zfill(width)
Where width is the length of the String.
Now see some of the examples of using the Python zfill() method:
- In the first example which has a width greater than the string length. It gives a new string containing 0 from left and is equals to width.
num = "125" str1 = num.zfill(10) print(str1)
OUTPUT: 0000000125
- We take a number string like “125” and have a width “10”. So that it will give zero’s from the left and then write number string.
- In the second, we declared width is less than string length. So it gives string as output.
txt = "I love Pyhton" str2 = txt.zfill(5) print(str2)
OUTPUT: I love Python
- We have to take a normal string or line and its length is less than the width of zfill(). So it will see as a normal string only.
- In this, we can use + or – and any decimal number to a string. It describes + or – includes before the zero fills to the left of our string. As you can see below, every value is filled after prefixing (+ or -) sign.
val1 = "+100" val2 = "-500" val3 = "20.00" str3 = val1.zfill(15) str4 = val2.zfill(15) str5 = val3.zfill(15) print(str3) print(str4) print(str5)
OUTPUT: +00000000000100 -00000000000500 000000000020.00
- We have taken 3 different numbers as “+”,”-” and “decimal” respectively and given zfiil() method each. So they will be printed as operator and then zero’s from the left.
Also Read: Generate Random Number String in Python
Leave a Reply