Python String zfill() Method

Pads a string on the left with zeros

Usage

The zfill() method returns a copy of string left padded with ‘0’ characters to make a string of length width.

The original string is returned, if width is less than or equal to string length.

Syntax

string.zfill(width)

Python string zfill() method parameters
ParameterConditionDescription
widthRequiredThe length of the string with zeros padded to the left

Basic Example

Example: Zero-pad a string until it is 6 characters long

S = '42'
x = S.zfill(6)
print(x)

Output:

000042

String with Sign Prefix

If the string contains a leading sign + or -, zeros are padded after the sign character rather than before.

Example: Zeros are padded after the sign

S = '+42'
x = S.zfill(6)
print(x)

S = '-42'
x = S.zfill(6)
print(x)

Output:

+00042-00042

Equivalent Method

You can achieve the same result by using format() method.

Example: Zero-pad a string with format()

S = '42'
x = '{:0>6}'.format(S)
print(x)

Output:

000042