How to pad a string with leading zeros in Python 3

How to pad a string with leading zeros in Python 3

Make use of the zfill() helper method to left-pad any string, integer or float with zeros; its valid for both Python 2.x and Python 3.x.

It important to note that Python 2 is no longer supported.

Sample usage:

print(str(1).zfill(3))
# Expected output: 001

Description:

When applied to a value, zfill() returns a value left-padded with zeros when the length of the initial string value less than that of the applied width value, otherwise, the initial string value as is.

Syntax:

str(string).zfill(width)
# Where string represents a string, an integer or a float, and
# width, the desired length to left-pad.

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(flength = {length:03})
length = 001

How to pad a string with leading zeros in Python 3

There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:

print(f{1:03})

Leave a Reply

Your email address will not be published. Required fields are marked *