Python 使用 str.format 添加前导零 [英] Python add leading zeroes using str.format

查看:120
本文介绍了Python 使用 str.format 添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否使用 str.format函数?

Can you display an integer value with leading zeroes using the str.format function?

示例输入:

"{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 的解决方案,以保持我的代码干净和一致(我还使用 datetime 属性格式化字符串)并扩展我对 格式规范迷你语言.

I know that both zfill and %-based formatting (e.g. '%03d' % 5) can accomplish this. However, I would like a solution that uses str.format in 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.

推荐答案

>>> "{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

这篇关于Python 使用 str.format 添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆