str.zfill()
Zero-pad numbers-as-strings: IDs, timestamps, sortable filenames.
Common call
"42".zfill(5)
Returns
new str, length ≥ width
Replaces
sign-aware: "-42".zfill(5) → "-0042"
Watch out
already-long strings come back unchanged — never truncated
str.zfill(widthwidth — Target minimum length. Shorter strings are padded; longer ones returned unchanged.type: int · required)
→ str
Demo
Live evaluation
Try:
Inputs
stringstrthe source
widthinttarget width
Output
'42'.zfill(5)
'00042'
Zeros are inserted after any leading sign, before the rest. A string already at or past the width is returned untouched — zfill never truncates. It pads any string, not just digits.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| width | int | yes | Target minimum length. Shorter strings are padded; longer ones returned unchanged. |
Return value
str — A copy left-padded with ASCII zeros to at least width characters. A leading sign stays in front of the padding.
Common patterns
Sortable numeric filenames
Zero-padding makes lexicographic order match numeric order.
name = f"img_{str(i).zfill(4)}.png" # img_0001.png … img_0042.png
Fixed-width IDs and codes
Invoice numbers, ZIP codes read from ints, etc.
invoice = str(n).zfill(8)
The f-string alternative
For numbers you are formatting anyway, :0Nd does it inline.
f"{i:04d}" # '0042' — same result, no str() call
Examples
1. Basic zero-padding
"42".zfill(5)
Returns
'00042'2. Sign stays in front
"-42".zfill(5)
Returns
'-0042'3. Longer than width
"123456".zfill(3)
Returns
'123456'4. Works on any string
"ab".zfill(4)
Returns
'00ab'Pitfalls
1. zfill pads — it never truncates
Fixed-width output needs an explicit slice for the overflow case.
Still 6 chars
"123456".zfill(3)
'123456'
If truncation is wanted
s.zfill(3)[-3:]
'456' — explicit choice
2. Only zfill is sign-aware — rjust is not
Padding with rjust(5, "0") puts zeros BEFORE the minus sign.
Broken number
"-42".rjust(5, "0")
'00-42'
Fix
"-42".zfill(5)
'-0042'
When to use
Use it
- Zero-padding strings you already have
- Sortable numeric filenames and IDs
Reach for something else
- Formatting a number directly → f"{n:04d}"
- Padding with other characters → str.rjust(width, char)
- Centering → str.center
Notes
Complexity
O(width)
Return
new str — source untouched
CPython impl
Objects/unicodeobject.c :: unicode_zfill
Memory
One new string of max(len, width)
Thread-safe
Yes — str is immutable
FAQ
If you have a number, format it directly with f"{n:04d}". zfill earns its keep when you already have a string (IDs read from files, user input).
History
2.2
Method added to str.