str.zfill()

Pads a string with zeros on the left up to a given length.

Returns
A new string padded with zeros.
Changes the original
No
On this page

Example

#
Python
for lesson in [1, 12, 105]:
    print("lesson_" + str(lesson).zfill(3))

print("-7".zfill(3))
print(f"{7:03d}")
Resultsaved result, you can check it
lesson_001
lesson_012
lesson_105
-07
007

Definition and usage

#

The zfill(width) method adds zeros at the start of the string until it reaches the given length. If the string is already longer, it stays unchanged.

It correctly handles the sign: "-7".zfill(3) gives "-07", meaning the zeros land after the minus sign.

For padding with other characters, use rjust(), ljust(), and center(), or the {n:03d} format in f-strings.

Syntax

#
Syntax
string.zfill(width)

Parameters

#
  • width

    int

    The target length of the string.

Good practices

#
  • File numbers with leading zeros (001, 002) sort correctly alphabetically.
  • In f-strings, the same effect comes from the {number:03d} format.

Related entries

#

Spotted a mistake or missing an example? Write to us.