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
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.
%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))
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With