假设我想显示数字123,其前面有可变数量的零。
例如,如果我想以5位数的形式显示它,则会使用digits = 5
,得到:
00123
如果我想要显示它为6个数字,我可以设置 digits = 6
,得到如下结果:000123
我该如何在Python中实现这个?
假设我想显示数字123,其前面有可变数量的零。
例如,如果我想以5位数的形式显示它,则会使用digits = 5
,得到:
00123
如果我想要显示它为6个数字,我可以设置 digits = 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)。
在Python 3.6中引入了格式化字符串字面量(简称"f-strings"),现在可以使用更简洁的语法访问先前定义的变量:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
In [1]: num=123
...: fill='0'
...: width=6
...: f'{num:{fill}{width}}'
Out[1]: '000123'
'%0*d' % (5, 123)
%0*d
中的 *
是什么意思?我查看了 Python 文档,发现在 format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]
中并没有 *
。 - SparkAndShine如果想要使用Python 3.6+和f-Strings实现相同的功能,可以采用以下解决方案。
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
s
是什么? - Dan Nissenbaumprint "%03d" % (43)
打印
043
"{:{}{}}".format(123, 0, 6)
。 - CodeManX.format
的情况下访问先前定义的变量。只需在字符串前面加上“f”:f'{num:{fill}{width}}'
。我已经添加了包含这些信息的答案。 - joelostblom