【问题标题】:Python add leading zeroes using str.format [duplicate]Python使用string.format添加前导零[重复]
【发布时间】:2013-06-11 16:02:50
【问题描述】:

您能否使用str.format 函数显示带有前导零的整数值?

输入示例:

"{0:some_format_specifying_width_3}".format(1)
"{0:some_format_specifying_width_3}".format(10)
"{0:some_format_specifying_width_3}".format(100)

期望的输出:

"001"
"010"
"100"

我知道基于zfill% 的格式(例如'%03d' % 5)都可以做到这一点。但是,我想要一个使用str.format 的解决方案,以保持我的代码干净和一致(我还使用日期时间属性格式化字符串)并扩展我对Format Specification Mini-Language 的了解。

【问题讨论】:

  • max_widthabc 变量名称还是您输入的字符串?
  • 这些只是一些示例变量名。 max_width 用于示例以指示示例值需要多少前导零。在我的实际代码中,格式化的输入包括一个日期时间对象和一些我想用前导零格式化的整数。
  • 所以你想要一个带有 format 的 1-liner 或者一个只使用原始 python 的函数就足够了?
  • 是的,我在问是否有可能(以及如何)只使用format

标签: python string python-2.7 string-formatting


【解决方案1】:
>>> "{0:0>3}".format(1)
'001'
>>> "{0:0>3}".format(10)
'010'
>>> "{0:0>3}".format(100)
'100'

解释:

{0 : 0 > 3}
 │   │ │ │
 │   │ │ └─ Width of 3
 │   │ └─ Align Right
 │   └─ Fill with '0'
 └─ Element index

【讨论】:

  • 啊,我觉得我的例子解释得有点过于字面意思了。我只是想要一种使"{0:some_format_specifying_width_four}".format(10) 产生"0010" 的格式。
  • 我更新了我的原始示例以提供更多清晰度
【解决方案2】:

源自 Python 文档中的 Format examples, Nesting examples

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

【讨论】:

  • 太棒了!我接受@F.J 的回答,因为我不喜欢为宽度指定另一个变量,尽管这个答案在其明确性上似乎非常pythonic!
  • 当您在回答问题后编辑问题时会发生这种情况。很高兴我们能帮助您澄清您的意图。
猜你喜欢
  • 2014-03-04
  • 2018-12-21
  • 2013-03-03
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多