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

# Zero-pad a string until it is 6 characters long
S = '42'
x = S.zfill(6)
print(x)
# Prints 000042

String with Sign Prefix

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

S = '+42'
x = S.zfill(6)
print(x)
# Prints +00042
S = '-42'
x = S.zfill(6)
print(x)
# Prints -00042

Equivalent Method

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

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