Last Updated : 02 Jan, 2025
zfill() method in Python is used to pad a string with zeros (0
) on the left until it reaches a specified width. In this article, we'll see how zfill() method works.
s = "42"
padded_text = s.zfill(5)
print(padded_text)
Explanation:
"42"
is padded with three zeros on the left to make its total length 5.zfill()
method ensures that the string is right-aligned and padded with zeros.Parametersstring.zfill(width)
Let's see how zfill()
behaves with a string shorter than the specified width:
s = "7"
padded_text = s.zfill(3)
print(padded_text)
Explanation:
"7"
has a length of 1.zfill(3)
method pads the string with two zeros on the left to make its total length 3.What happens when the string length matches the specified width?
Python
s = "12345"
padded_text = s.zfill(5)
print(padded_text)
Explanation:
"12345"
already has a length of 5.Let’s see how zfill() handles a string longer than the specified width:
Python
s = "Python"
padded_text = s.zfill(4)
print(padded_text)
Explanation:
"Python"
has a length of 6, which is greater than the specified width of 4.zfill()
with negative and positive numbers
When dealing with strings representing numbers, the zfill()
method correctly handles the sign:
#positive and negative numbers
s1 = "42"
s2 = "-42"
print(s1.zfill(5))
print(s2.zfill(5))
Explanation:
"42"
, zeros are added to the left to make its total length 5."-42"
, the minus sign is preserved, and zeros are added after the sign to maintain the width.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4