str.zfill()
Adds zeros to the left of a string until it reaches the width you ask for, keeping a + or - sign at the front.
str.zfill(width)zfill() puts zeros in front of a string until it is width characters long: "42".zfill(5) gives "00042". The "z" stands for zero.
Use it for fixed-width codes and numbers: invoice numbers, file names that sort correctly (photo_007.jpg), or times like "09:05".
It knows about signs: "-42".zfill(5) gives "-0042", with the zeros after the minus. A string that is already long enough comes back unchanged, never cut. It is a string method, so a number must be turned into text first.
Parameters
| Parameter | What it is |
|---|---|
widthrequired | The length the result should have. If the string is already this long or longer, nothing is added. |
Return value
A new string, padded with zeros on the left.
Examples
1Pad numbers with zeros
print("42".zfill(5))
print("7".zfill(3))
print("12345".zfill(3))00042 007 12345
2Signs stay in front
print("-42".zfill(5))
print("+7".zfill(4))-0042 +007
3Invoice numbers from integers
for n in [1, 23, 456]:
print("INV-" + str(n).zfill(4))INV-0001 INV-0023 INV-0456
str(n) first: integers have no zfill().
4Show a time
hours, minutes = 9, 5
print(str(hours).zfill(2) + ":" + str(minutes).zfill(2))
print(f"{hours:02d}:{minutes:02d}")09:05 09:05
The f-string format 02d does the same for numbers.
Common mistakes
Calling zfill() on a number
Integers have no zfill() method and raise AttributeError. Convert with str() or use a format such as f"{n:05d}".
n = 42
try:
n.zfill(5)
except AttributeError:
print("AttributeError: int has no zfill()")
print(str(n).zfill(5))AttributeError: int has no zfill() 00042
Questions people ask
How do I pad with another character?
Use str.rjust(): "42".rjust(5, "*") gives "***42".
How do I add zeros on the right?
Use str.ljust(): "4.5".ljust(5, "0") gives "4.500".
zfill() or an f-string?
For numbers, f"{n:05d}" is common. For text that is already a string, zfill() is simplest.