假设我想显示数字 123,并在前面添加可变数量的填充零。
例如,如果我想以 5 位数字显示它,我会digits = 5
给我:
00123
如果我想以 6 位数字显示它,我会digits = 6
giving:
000123
我将如何在 Python 中做到这一点?
如果您在格式化字符串中使用它format()
优于旧风格的方法''%
格式化
>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
See
http://docs.python.org/library/stdtypes.html#str.format http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings http://docs.python.org/library/string.html#formatstrings
这是一个可变宽度的示例
>>> '{num:0{width}}'.format(num=123, width=6)
'000123'
您甚至可以将填充字符指定为变量
>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)