动态格式化字符串
如果我想让我的格式化字符串可以动态调整,我可以把下面的代码从
print '%20s : %20s' % ("Python", "Very Good")
改成
width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")
不过,这里字符串拼接起来感觉有点麻烦。有没有其他方法可以简化一下?
5 个回答
34
如果你想用 Python 3.6 及以上版本和 f-字符串 来做同样的事情,这里有个解决方案。
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
125
你可以使用 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'
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])