string - 固定宽度数字格式化python 3

标签 string formatting python-3.x string-formatting fixed-width

如何使用 format 属性在 python 3.2 中获取整数以将 0 填充到固定宽度? 示例:

a = 1
print('{0:3}'.format(a))

给出我想要的“1”而不是“001”。在 python 2.x 中,我知道这可以使用

print "%03d" % number. 

我检查了 python 3 字符串文档,但没能得到它。

http://docs.python.org/release/3.2/library/string.html#format-specification-mini-language

谢谢。

最佳答案

在宽度前加上 0:

>>> '{0:03}'.format(1)
'001'

此外,在最新版本的 Python(不确定是哪个,但至少 2.7 和 3.1)中,您不需要位置标记:

>>> '{:03}'.format(1)
'001'

关于string - 固定宽度数字格式化python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6869999/

相关文章:

减法时PHP浮点计算错误

android - 字符串中的间距

python - marshal.loads 函数不会将 *.pyc 内容加载到代码对象

Scala函数获取字母表中的下一个字母

string - 如何在coffeescript中将数字转换为字符串?

python - 解析可变长度数据

如果 On 不存在,C++ 在文件末尾添加新行?

python - 为什么包装random.Random的random方法好像对RNG有影响?

python - 在 for 循环中使用 unpack 与在 python 中不使用 unpack 有什么区别

c++ - 我什么时候会通过 const& std::string 而不是 std::string_view?