Python String zfill() method
The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified width.
Syntax
1 2 3 |
string.zfill(width) |
Parameter
width – This parameter represents a number specifying the position of the element you want to remove.
Return
This method returns the numeric string left filled with zeros in a string of length width.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python program explaining # the string.zfill() method # initializing the string string = "Hello World" # it will add zeros at the starting of the string # returning total 25 width string print(string.zfill(25)) # it will add zeros at the starting of the string # returning total 20 width string print(string.zfill(20)) # Given length is less than # the length od original string # it will return the same string print(string.zfill(10)) |
Output
1 2 3 4 5 |
00000000000000Hello World 000000000Hello World Hello World |
Example 2
1 2 3 4 5 6 7 8 9 |
# Python program explaining # the string.zfill() method # initializing the string string = "This is a Python example" #passing negative number # return the same string print(string.zfill(-25)) |
Output
1 2 3 |
This is a Python example |
Example 3
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Python program explaining # the string.zfill() method # initializing the string with whitespaces string = " hello\n" print(string.zfill(15)) # string with integers string="653444" print(string.zfill(13)) # initialising string with special characters string= "*-6453436" print(string.zfill(15)) |
Output
1 2 3 4 5 |
000000 hello 0000000653444 000000*-6453436 |