Python String zfill() method is used to add zeros (0) to the left side of string until it reaches the specified width. This method also works with strings containing different prefixes and signs (+/-).
Syntax
string.zfill(width)
Parameters
width(required): It is the length of the string that we want to make.
Return Value
It returns a copy of the string with the required number of zeroes padded to the left side of the main string.
Visual Representation
Example 1: How to Use String zfill() Method
h1= "Ronaldo"
print(h1.zfill(10))
print(h1.zfill(8))
print(h1.zfill(12))
Output
000Ronaldo
0Ronaldo
00000Ronaldo
Example 2: Width is lesser than the length of the string
It returns the original string if the width is lesser than the length of the string.”
h1 = "50.00"
print(h1.zfill(4))
Output
50.00
It works with any string, not necessarily a numeric string.
h1 = "Ronaldo"
print(data.zfill(6))
Output
Ronaldo
Example 3: How does zfill() work with Sign Prefix?
nm = '#100'
print(nm.zfill(6))
nm = '$100'
print(nm.zfill(7))
nm = '-100'
print(nm.zfill(9))
nm = '+100'
print(nm.zfill(9))
Output
00#100
000$100
-00000100
+00000100
This method pads with leading zeros (0) subsequent to any sign character ( + or -), whereas other symbols, such as # are treated as regular characters, with zeros prepended before them.
Example 4: TypeError
If the width parameter is not specified, it will raise a TypeError.
h1 = "79"
print(h1.zfill())
Output
TypeError: str.zfill() takes exactly one argument (0 given)
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.