How do I format a number with a variable number of digits in Python?

Say I wanted to display the number 123 with a variable number of padded zeroes on the front.

For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:

00123

If I wanted to display it in 6 digits I would have digits = 6 giving:

000123

How would I do this in Python?

82096 次浏览

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

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

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

'%0*d' % (5, 123)
print "%03d" % (43)

指纹

043

使用字符串格式设置

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

More info here: 链接文本

如果您使用 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'

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

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'

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

>>> 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'

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

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")