close

How to pad a string with leading zeros in Python 3

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to pad a string with leading zeros in Python 3 in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to pad a string with leading zeros in Python 3?

  1. 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; it's valid for both Python 2.x and Python 3.x.

  2. 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; it's valid for both Python 2.x and Python 3.x.

Method 1

Make use of the zfill() helper method to left-pad any string, integer or float with zeros; it’s 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.

Method 2

Since python 3.6 you can use fstring :

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read