72

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

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

00123

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

000123

我将如何在 Python 中做到这一点?

4

7 回答 7

194

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

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

请参阅
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'

您甚至可以将填充字符指定为变量

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'
于 2010-07-12T13:23:15.950 回答
42

有一个叫做 zfill 的字符串方法:

>>> '12344'.zfill(10)
0000012344

它将用零填充字符串的左侧以使字符串长度为 N(在本例中为 10)。

于 2010-07-12T13:17:55.473 回答
24
'%0*d' % (5, 123)
于 2010-07-12T13:19:41.077 回答
22

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

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

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

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

Out[1]: '000123'
于 2017-05-26T15:39:40.443 回答
13

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

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
于 2020-02-27T16:32:20.693 回答
5
print "%03d" % (43)

印刷

043

于 2010-07-12T13:20:41.813 回答
1

使用字符串格式

print '%(#)03d' % {'#': 2}
002
print '%(#)06d' % {'#': 123}
000123

更多信息在这里:链接文本

于 2010-07-12T13:20:53.713 回答