Python Reference ยท String Methods
Python str.zfill() method
Reference for Python str.zfill(): pad a string with zeros on the left to a given width, how signs are handled, and when to use format() or rjust() instead.
The zfill(width) method returns a copy of the string padded on the left with the character "0" until it is width characters long. It exists for the common job of producing fixed-width numbers such as 007, 2026-03-05 parts, or file names like frame_0042.png.
Unlike rjust(width, "0"), zfill() understands a leading sign: the zeros go after a + or -, so negative numbers stay readable. If the string is already width characters or longer, it is returned unchanged.
print("42".zfill(5)) # 00042
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.zfill(width)
| Name | Description |
|---|---|
width |
The minimum length of the result, as an integer. A value less than or equal to the string's length changes nothing. |
Return value: a new string. The original is not modified.
Raises: a TypeError if width is not an integer.
Usage notes
- Works on strings only.
zfill()is a string method, so convert numbers first:str(7).zfill(3). Calling(7).zfill(3)raisesAttributeError. - Sign aware. A leading
+or-stays at the front and the zeros are inserted after it:"-42".zfill(5)is"-0042". The sign counts toward the width. - Never truncates. Longer strings come back whole.
- Pads with zeros only. For other pad characters use
rjust(width, fill),ljust()orcenter(). - Not only for digits. Any text can be padded, so
"abc".zfill(5)gives"00abc". Check your input if that is not what you want. - Format specs are often nicer.
f"{n:05d}"orformat(n, "05d")pads and formats a number in one step and avoids thestr()call. Floats work too:f"{3.5:06.2f}"gives003.50. - Bytes and bytearray have their own
zfill()that pads with the ASCII digit zero.