Python String zfill() Method
The zfill()
method returns a copy of the string with '0' characters padded to the left. It adds zeros (0) at the beginning of the string until the length of a string equals the specified width
parameter.
A leading sign ('+'/'-') is handled by inserting the padding after the sign character.
If the value of the width
parameter is less than the length of the string, no filling is done.
Syntax:
str.zfill(width)
Parametrs:
- width: (Required) The length of the returned string with 0's padded to the left of the original string.
Return Value:
- Returns copy of the original string with 0's padded at the beginning if width is greater than the length of the string.
- Returns original string without any changes if the width is lesser than the length of the string.
The following example demonstrates the zfill()
method.
num = '100'
print(num.zfill(5))
num = '-100' # with - sign
print(num.zfill(5))
num = '$100' # with $ sign
print(num.zfill(5))
00100
-0100
0$100
Above, the zfill()
method will add zeros after the + or - sign, but not after any other symbol such as $, #, etc.
The zfill()
method will return the original string if the width is lesser than the length of the string, as shown below.
mystr = '10.00'
print(mystr.zfill(5))
10.00
It works with any string, not necessarily a numeric string.
mystr = '10A'
print(mystr.zfill(5))
0010A
If the width
parameter is not specified, then it will raise a TypeError
.
num = '100'
print(num.zfill())
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
num.zfill()
TypeError: zfill() takes exactly one argument (0 given)