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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:30:41  来源:igfitidea点击:

Python add leading zeroes using str.format

pythonstringpython-2.7string-formatting

提问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:

源自格式示例,Python 文档中的嵌套示例

>>> '{0:0{width}}'.format(5, width=3)
'005'