How to pad a string with leading zeros in Python 3

PythonPython 3.xMathRounding

Python Problem Overview


I'm trying to make length = 001 in Python 3 but whenever I try to print it out it truncates the value without the leading zeros (length = 1). How would I stop this happening without having to cast length to a string before printing it out?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Since python 3.6 you can use fstring :

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

Solution 3 - Python

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

print(f"{1:03}")

Solution 4 - Python

Python integers don't have an inherent length or number of significant digits. If you want them to print a specific way, you need to convert them to a string. There are several ways you can do so that let you specify things like padding characters and minimum lengths.

To pad with zeros to a minimum of three characters, try:

length = 1
print(format(length, '03'))

Solution 5 - Python

I suggest this ugly method but it works:

length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)

I came here to find a lighter solution than this one!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGabby FreelandView Question on Stackoverflow
Solution 1 - PythonnyedidikekeView Answer on Stackoverflow
Solution 2 - PythonPhEView Answer on Stackoverflow
Solution 3 - PythonAnatolView Answer on Stackoverflow
Solution 4 - PythonBlckknghtView Answer on Stackoverflow
Solution 5 - PythonwydadmanView Answer on Stackoverflow