假设我想在前面显示带有可变数量的填充零的数字 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)。
'%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