Python String zfill() Method
The zfill()
method pads a string on the left with zeros (0
) until it reaches a specified width. It is useful for formatting numeric strings with fixed width (e.g., “001"
, "002"
, …, "010"
.
Syntax
string.zfill(width)
Parameters
No parameters.
Return Value
Returns a new string padded with zeros on the left to meet the specified width.
If the width
is smaller than or equal to the string length, the original string is returned.
Examples
Zero Padding a String in Python
text = "35"
print(text.zfill(5)) # Output: 00035
With Negative or Positive Sign
If the string starts with a positive or negative sign, the zeros are added after the sign.
text = "-35"
print(text.zfill(5)) # Output: -00035
text2 = "+35"
print(text2.zfill(5)) # Output: +0035
Width Smaller Than or Equal to String Length
If the width
is smaller than or equal to the string length, the original string is returned.
text = "12345"
print(text.zfill(3)) # Output: 12345