Tutorial Study Image

Python zfill()

The zfill() function in python helps to return the copy of the string after adding zeros at the beginning of the string until it reaches the given width.


str.zfill(width) #where width is a integer value
 

zfill() Parameters:

The zfill() function takes a single parameter. If the given width is less than the length of the string, zero fillings are not performed

Parameter Description Required / Optional
width specifies the length of the returned string from zfill() Required

zfill() Return Value

The return value is a  string. If the string started with the prefix '+' or  '-' sign, the zeros are added after this prefix.

Input Return Value
width string with left padded zeros

Examples of zfill() method in Python

Example 1:Working of zfill() in Python


string = "python programming"
print(string.zfill(20))
print(string.zfill(25))
print(string.zfill(19))
# given width less than string length
print(string.zfill(15))
 

Output:


000python programming
00000000python programming
00python programming
python programming

Example 2: How zfill() works with Sign Prefix(+ or -)?


N = "-330"
print(number.zfill(10))

N = "+480"
print(number.zfill(10))

str = "--check+sting"
print(str.zfill(18))
 

Output:


-000000330
+000000480
-000000-check+sting