动态格式化字符串

时间:2010-11-29 08:59:58

标签: python string

如果我想让格式化的字符串动态调整,我将从

更改以下代码
print '%20s : %20s' % ("Python", "Very Good")

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

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

5 个答案:

答案 0 :(得分:56)

您可以使用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'

答案 1 :(得分:28)

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

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])

答案 2 :(得分:6)

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

答案 3 :(得分:2)

如果您不想同时指定宽度,您可以提前准备格式字符串,就像您正在做的那样 - 但需要另外替换。我们使用%%来转义字符串中的实际%符号。当宽度为20时,我们希望在格式字符串中以%20s结束,因此我们使用%%%ds并提供宽度变量以替换它。前两个%符号变为文字%,然后%d被变量替换。

因此:

format_template = '%%%ds : %%%ds'
# later:
width = 20
formatter = format_template % (width, width)
# even later:
print formatter % ('Python', 'Very Good')

答案 4 :(得分:0)

对于那些想使用python 3.6+和f-Strings做同样事情的人,这是解决方案。

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