Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python format Integer into fixed length strings [duplicate]

Tags:

python

I want to generate a string based on an int along with zeros. And the length should always be of 5 not more then that nor less.

For example:  Consider a Integer: 1 Formatted String : 00001  Consider a Integer: 12 Formatted String : 00012  Consider a Integer: 110 Formatted String : 00110  Consider a Integer: 1111 Formatted String : 01111  Consider a Integer: 11111 Formatted String : 11111 
like image 563
Vaibhav Jain Avatar asked Oct 19 '14 02:10

Vaibhav Jain


People also ask

How do I fix the length of a string in Python?

In Python, strings have a built-in method named ljust . The method lets you pad a string with characters up to a certain length. The ljust method means "left-justify"; this makes sense because your string will be to the left after adjustment up to the specified length.

What is %d and %s in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))

How do I format an int to a string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

How does %D work in Python?

The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.


1 Answers

Use the format() function or the str.format() method to format integers with zero-padding:

print format(integervalue, '05d') print 'Formatted String : {0:05d}'.format(integervalue) 

See the Format Specification Mini-Language; the leading 0 in the format signifies 0-padding, the 5 is the minimal field width; any number shorter than that is padded to the full width.

Demo:

>>> format(110, '05d') '00110' >>> 'Formatted String : {0:05d}'.format(12) 'Formatted String : 00012' 
like image 161
Martijn Pieters Avatar answered Sep 19 '22 09:09

Martijn Pieters