繁体   English   中英

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

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

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

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

00123

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

000123

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

如果您在格式化字符串中使用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'

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

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

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

'%0*d' % (5, 123)

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

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

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

印刷

043

使用字符串格式

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM