Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad a string with leading zeros in Python 3 [duplicate]

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?

like image 643
Gabby Freeland Avatar asked Sep 09 '16 02:09

Gabby Freeland


People also ask

How do I add a zero padding in Python?

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

How do you add leading zeros to a string in Python?

For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.

How can I pad a value with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.

How do you add padding to a string in Python?

The standard way to add padding to a string in Python is using the str. rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.


1 Answers

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. 
like image 76
nyedidikeke Avatar answered Oct 14 '22 11:10

nyedidikeke