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

ParameterDescription
width Total length of the result.

Return value

A new string.

Examples

Pad with zerosTry it yourself
print("42".zfill(5), "-42".zfill(5), "12345".zfill(3))

Output

00042 -0042 12345
Fixed-width file namesTry it yourself
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

VersionChange
Python 3.0Added