Python 使用 str.format 添加前导零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17118071/
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 add leading zeroes using str.format
提问by butch
Can you display an integer value with leading zeroes using the str.formatfunction?
您可以使用该str.format函数显示带前导零的整数值吗?
Example input:
示例输入:
"{0:some_format_specifying_width_3}".format(1)
"{0:some_format_specifying_width_3}".format(10)
"{0:some_format_specifying_width_3}".format(100)
Desired output:
期望的输出:
"001"
"010"
"100"
I know that both zfilland %-based formatting (e.g. '%03d' % 5) can accomplish this. However, I would like a solution that uses str.formatin order to keep my code clean and consistent (I'm also formatting the string with datetime attributes) and also to expand my knowledge of the Format Specification Mini-Language.
我知道基于zfilland%的格式(例如'%03d' % 5)可以实现这一点。但是,我想要一个解决方案,用于str.format保持我的代码干净和一致(我还使用 datetime 属性格式化字符串)并扩展我对Format Specification Mini-Language 的知识。
采纳答案by Andrew Clark
>>> "{0:0>3}".format(1)
'001'
>>> "{0:0>3}".format(10)
'010'
>>> "{0:0>3}".format(100)
'100'
Explanation:
解释:
{0 : 0 > 3}
│ │ │ │
│ │ │ └─ Width of 3
│ │ └─ Align Right
│ └─ Fill with '0'
└─ Element index
回答by msw
Derived from Format examples, Nesting examplesin the Python docs:
>>> '{0:0{width}}'.format(5, width=3)
'005'

