【发布时间】:2011-03-14 19:40:19
【问题描述】:
假设我想在前面显示数字 123,并在前面填充可变数量的零。
例如,如果我想以 5 位数字显示它,我将有 digits = 5 给我:
00123
如果我想以 6 位数字显示它,我会给出 digits = 6:
000123
我将如何在 Python 中做到这一点?
【问题讨论】:
标签: python string string-formatting number-formatting
假设我想在前面显示数字 123,并在前面填充可变数量的零。
例如,如果我想以 5 位数字显示它,我将有 digits = 5 给我:
00123
如果我想以 6 位数字显示它,我会给出 digits = 6:
000123
我将如何在 Python 中做到这一点?
【问题讨论】:
标签: python string string-formatting number-formatting
如果您在格式化字符串中使用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'
【讨论】:
% 样式更干净,这对我来说很讽刺,因为我曾经觉得% 样式是最干净的方法。
"{:{}{}}".format(123, 0, 6).
.format。只需在字符串前面加上 f:f'{num:{fill}{width}}'。我用这个信息添加了一个答案。
有一个叫zfill的字符串方法:
>>> '12344'.zfill(10)
0000012344
它将用零填充字符串的左侧以使字符串长度为 N(在本例中为 10)。
【讨论】:
'%0*d' % (5, 123)
【讨论】:
* 中的%0*d 是什么意思?我检查 Python 文档。 * 不在format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] 中。
使用 Python 3.6 中的the introduction of formatted string literals(简称“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}")
【讨论】:
s 是什么?
print "%03d" % (43)
打印
043
【讨论】:
【讨论】: