Python 3 reference · String Methods
Python String zfill() Method
Return the string padded on the left with zeros to the given width, keeping a leading + or - sign in front.
Python 3 Since 3.0
Syntax
str.zfill(width)
Parameters
| Parameter | Description |
|---|---|
width |
Total length of the result. |
Return value
A new string.
Examples
print("42".zfill(5), "-42".zfill(5), "12345".zfill(3))
Output
00042 -0042 12345
for n in [1, 12, 123]:
print(f"img_{str(n).zfill(3)}.png")
print(f"{7:03d}") # the same with formatting
Output
img_001.png img_012.png img_123.png 007
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.rjust()· Return the string right-justified in a field of the given width, padded on the left with a fill character.str.center()· Return the string centred in a field of the given width, padded on both sides with a fill character (a space by default).str.format()· Return a formatted string, filling {} placeholders with the arguments. f-strings are usually simpler.- Python Strings · tutorial