Python 动态格式化字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4302166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:10:12  来源:igfitidea点击:

Format string dynamically

pythonstring

提问by Cheok Yan Cheng

If I want to make my formatted string dynamically adjustable, I can change the following code from

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

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

to

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

However, it seems that string concatenation is cumbersome here. Any other way to simplify things?

但是,这里的字符串连接似乎很麻烦。有没有其他方法可以简化事情?

采纳答案by Frédéric Hamidi

You can fetch the padding value from the argument list:

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

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

You can even insert the padding values dynamically:

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

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

回答by Ignacio Vazquez-Abrams

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

回答by Karl Knechtel

If you don't want to specify the widths at the same time, you can prepare a format string ahead of time, like you were doing - but with another substitution. We use %%to escape actual % signs in a string. We want to end up with %20sin our format string when the width is 20, so we use %%%dsand supply the width variable to substitute in there. The first two % signs become a literal %, and then %d is substituted with the variable.

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

Thus:

因此:

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

回答by styvane

You can do this using the str.format()method.

您可以使用该str.format()方法执行此操作。

>>> width = 20
>>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
              Python :            Very Good

Starting from Python 3.6 you can use f-stringto do this:

从 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'

回答by Praveen Kulkarni

For those who want to do the same thing with python 3.6+ and f-Stringsthis is the solution.

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

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