The Python String zfill() method is a built-in function that adds zeros (0) at the beginning of the string until it reaches the specified length and returns the copy of a string.
Syntax
The Syntax of zfill()
method is:
str.zfill(width)
Parameters
The zfill()
method does a single parameter width.
- width – The length of the string returned from
zfill()
after padding with zeros (0) from the left side of the string.
Return Value
The zfill()
method returns the copy of a string padded with zeros (0) to the left. The length of the string depends on the width argument provided.
For example, if the initial string length is 10 and the width specified is 15, the zfill()
method returns a copy of the string with five zeros (0) filled to the left.
Suppose the initial string length is 10 and the width specified is 5. In this case, the zfill()
method does not fill zeros to the string and returns the original string as-is. The length of the string remains 10 in this case.
Note: If the string starts with a prefix like ('+','-'
), the zeros are appended after the first sign.
Example 1: How zfill() function works in Python
text = "Python Programming"
print(text.zfill(25))
print(text.zfill(20))
# returns as-is because the width given
# is less than the length of string
print(text.zfill(10))
Output
0000000Python Programming
00Python Programming
Python Programming
Example 2: zfill() method in case of sign prefix
If the string starts with a prefix like ('+','-'
), the zeros are appended after the first sign.
number = "+12345"
print(number.zfill(10))
number = "-5733"
print(number.zfill(8))
text = "--56text-python"
print(text.zfill(20))
Output
+000012345
-0005733
-00000-56text-python