如何在Python中格式化具有可变位数的数字?

Edd*_*ddy 57 python string string-formatting number-formatting

假设我想在前面显示带有可变数量的填充零的数字123.

例如,如果我想以5位数显示它,我会有数字= 5给我:

00123
Run Code Online (Sandbox Code Playgroud)

如果我想以6位数显示它,我会有数字= 6给出:

000123
Run Code Online (Sandbox Code Playgroud)

我将如何在Python中执行此操作?

Joh*_*ooy 161

如果您在格式化的字符串中使用它,其format()方法比旧样式''%格式更受欢迎

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
Run Code Online (Sandbox Code Playgroud)

请参阅
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings

这是一个宽度可变的例子

>>> '{num:0{width}}'.format(num=123, width=6)
'000123'
Run Code Online (Sandbox Code Playgroud)

您甚至可以将fill char指定为变量

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
Run Code Online (Sandbox Code Playgroud)

  • 还支持未命名的文件夹(至少在Python 3.4中):`"{:{} {}}".format(123,0,6)`. (6认同)
  • 提及新格式方法的+1.这需要一些时间来习惯,但我觉得它比旧的`%`风格更清洁,这对我来说很讽刺,因为我曾经觉得'%`风格是最干净的方法. (4认同)
  • @CoDEmanX未命名的占位符也适用于python 2.7 - 谢谢. (2认同)
  • 随着Python 3.6中引入的f字符串,现在可以访问以前定义的变量,而无需使用.format。只需在字符串前加上一个“ f”即可:“ f” {num:{fill} {width}}'。我对此信息添加了答案。 (2认同)

Don*_*ner 36

有一个名为zfill的字符串方法:

>>> '12344'.zfill(10)
0000012344
Run Code Online (Sandbox Code Playgroud)

它将用零填充字符串的左侧以使字符串长度为N(在这种情况下为10).


Ign*_*ams 18

'%0*d' % (5, 123)
Run Code Online (Sandbox Code Playgroud)

  • ["最小字段宽度(可选)。如果指定为'*'(星号),则从值中元组的下一个元素读取实际宽度,并且要转换的对象在最小字段宽度和可选精度之后。 "](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) (4认同)

Pra*_*rni 11

对于那些想用 python 3.6+ 和f-Strings做同样事情的人来说,这是解决方案。

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
Run Code Online (Sandbox Code Playgroud)


joe*_*lom 7

随着Python 3.6 中格式化字符串文字(简称为“ f-strings”)的引入,现在可以使用更简短的语法访问先前定义的变量:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
Run Code Online (Sandbox Code Playgroud)

John La Rooy给出的示例可以写成

In [1]: num=123
   ...: fill='0'
   ...: width=6
   ...: f'{num:{fill}{width}}'

Out[1]: '000123'
Run Code Online (Sandbox Code Playgroud)


st0*_*0le 5

print "%03d" % (43)
Run Code Online (Sandbox Code Playgroud)

打印

043