Python format Integer into fixed length strings [duplicate]
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
Solution 1:
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'