如何在Python中格式化具有可变位数的数字?
假设我想在数字123前面加上不同数量的零,让它看起来更长。
比如说,如果我想让它显示成5位数,我就可以设置 digits = 5
,这样就会得到:
00123
如果我想让它显示成6位数,我就可以设置 digits = 6
,这样就会得到:
000123
那么我该怎么在Python中实现这个呢?
7 个回答
31
在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'
213
如果你在使用格式化字符串时,建议用 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'
45
有一个字符串的方法叫做 zfill:
>>> '12344'.zfill(10)
0000012344
这个方法会在字符串的左边加上零,直到字符串的长度达到 N(在这个例子中是 10)。