动态格式化字符串

73

如果我想使我的格式化字符串动态可调整,我可以将以下代码更改为

print '%20s : %20s' % ("Python", "Very Good")

width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")

不过,似乎这里字符串连接很麻烦。还有其他简化的方法吗?

5个回答

123
你可以使用 str.format() 方法实现此操作。
>>> width = 20
>>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
              Python :            Very Good

从Python 3.6开始,您可以使用f-string来实现此功能:

In [579]: lang = 'Python'

In [580]: adj = 'Very Good'

In [581]: width = 20

In [582]: f'{lang:>{width}}: {adj:>{width}}'
Out[582]: '              Python:            Very Good'

我们可以将它对齐到左边吗? - alper
格式化规范(format-specification)@alper - styvane

42

您可以从参数列表中获取填充值:

print '%*s : %*s' % (20, "Python", 20, "Very Good")

你甚至可以动态地插入填充值:

width = 20
args = ("Python", "Very Good")
padded_args = zip([width] * len(args), args)
# Flatten the padded argument list.
print "%*s : %*s" % tuple([item for list in padded_args for item in list])

33

对于那些想要使用Python 3.6+和f-Strings来完成相同操作的人,这是解决方案。

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

2
谢谢。这正是我在寻找的。另外一个问题,变量前面的“>”有什么作用?我看到其他人使用的是前面带有“0”。这有什么特殊意义吗? - Heather Claxton
2
实际上,我刚刚找到了答案。'>'和'<'分别用于数字的右对齐和左对齐。以下是来源:http://cis.bentley.edu/sandbox/wp-content/uploads/Documentation-on-f-strings.pdf - Heather Claxton

8
print '%*s : %*s' % (width, 'Python', width, 'Very Good')

+1 这个回答比我的好。我一直在看 ljust 和 rjust 函数来实现这个。 - pyfunc

2
如果您不想同时指定宽度,可以预先准备格式字符串,就像您正在做的那样——但使用另一个替换。我们使用%%来转义字符串中实际的%号。当宽度为20时,我们希望最终得到%20s,因此我们使用%%%ds并提供要在其中替换的宽度变量。前两个%号成为一个文字%,然后%d用变量替换。
因此:
format_template = '%%%ds : %%%ds'
# later:
width = 20
formatter = format_template % (width, width)
# even later:
print formatter % ('Python', 'Very Good')

1
我喜欢这种动态生成格式字符串的方式。然而,如果只需要动态插值字段宽度,Hamidi先生的方法更好。 - Jim Dennis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接