Python将整数格式化为固定长度字符串

Python将整数格式化为固定长度字符串,python,Python,我想根据int和零生成一个字符串。长度应始终为5,不得大于或小于该值 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 Con

我想根据
int
和零生成一个字符串。长度应始终为
5
,不得大于或小于该值

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
使用或方法格式化带零填充的整数:

print format(integervalue, '05d')
print 'Formatted String : {0:05d}'.format(integervalue)
看,;格式中的前导
0
表示0-padding,
5
表示最小字段宽度;任何短于此的数字都将填充到全宽

演示:


我发现这也很有用:
print“position:{0:5d},fix id:{1}填充的等待时间为秒:{2:03d}.format(12453585,89)”
我的意思是,你可以避免用0填充(如在position中)@RodrigoLaguna:当然,但这个问题特别要求用零填充。:-)
>>> format(110, '05d')
'00110'
>>> 'Formatted String : {0:05d}'.format(12)
'Formatted String : 00012'