如果我想使我的格式化字符串动态可调整,我可以将以下代码更改为
print '%20s : %20s' % ("Python", "Very Good")
到
width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")
不过,似乎这里字符串连接很麻烦。还有其他简化的方法吗?
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'
您可以从参数列表中获取填充值:
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])
对于那些想要使用Python 3.6+和f-Strings来完成相同操作的人,这是解决方案。
width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
print '%*s : %*s' % (width, 'Python', width, 'Very Good')
%%
来转义字符串中实际的%号。当宽度为20时,我们希望最终得到%20s
,因此我们使用%%%ds
并提供要在其中替换的宽度变量。前两个%号成为一个文字%,然后%d用变量替换。format_template = '%%%ds : %%%ds'
# later:
width = 20
formatter = format_template % (width, width)
# even later:
print formatter % ('Python', 'Very Good')