Format string dynamically
如果我想使格式化字符串动态可调,我将从
1 | print '%20s : %20s' % ("Python","Very Good") |
到
1 2 | width = 20 print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python","Very Good") |
然而,这里的字符串连接似乎很麻烦。还有其他简化方法吗?
您可以使用
1 2 3 | >>> width = 20 >>> print("{:>{width}} : {:>{width}}".format("Python","Very Good", width=width)) Python : Very Good |
从python 3.6开始,您可以使用
1 2 3 4 5 6 7 8 | 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 | print '%*s : %*s' % (20,"Python", 20,"Very Good") |
甚至可以动态插入填充值:
1 2 3 4 5 | 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]) |
1 | print '%*s : %*s' % (width, 'Python', width, 'Very Good') |
如果您不想同时指定宽度,可以像以前那样提前准备一个格式字符串,但使用另一个替换。我们使用
因此:
1 2 3 4 5 6 | format_template = '%%%ds : %%%ds' # later: width = 20 formatter = format_template % (width, width) # even later: print formatter % ('Python', 'Very Good') |
对于那些想用python 3.6+和f-strings做同样事情的人来说,这就是解决方案。
1 2 3 | width = 20 py, vg ="Python","Very Good" print(f"{py:>{width}s} : {vg:>{width}s}") |