Python 将整数格式化为定长字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26446758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python format Integer into fixed length strings
提问by vaibhav jain
I want to generate a string based on an intalong with zeros. And the length should always be of 5not more then that nor less.
我想生成一个基于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
采纳答案by Martijn Pieters
Use the format()functionor the str.format()method to format integers with zero-padding:
使用format()函数或str.format()方法用零填充格式化整数:
print format(integervalue, '05d')
print 'Formatted String : {0:05d}'.format(integervalue)
See the Format Specification Mini-Language; the leading 0in the format signifies 0-padding, the 5is the minimal field width; any number shorter than that is padded to the full width.
请参阅格式规范迷你语言;0格式中的前导表示 0-padding,5即最小字段宽度;任何比它短的数字都填充到全宽。
Demo:
演示:
>>> format(110, '05d')
'00110'
>>> 'Formatted String : {0:05d}'.format(12)
'Formatted String : 00012'

