Python使用str.format函数添加前导零

6 浏览
0 Comments

Python使用str.format函数添加前导零

你可以使用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的解决方案,以保持我的代码简洁和一致(我还在使用datetime属性格式化字符串),并且扩展我对格式规范迷你语言的了解。

0