Python String zfill() method
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
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
# 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
00000000000000Hello World 000000000Hello World Hello World
Example 2
# 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
This is a Python example
Example 3
# 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
000000 hello 0000000653444 000000*-6453436