动态格式化字符串

Che*_*eng 45 python string

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

print '%20s : %20s' % ("Python", "Very Good")
Run Code Online (Sandbox Code Playgroud)

width = 20
print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")
Run Code Online (Sandbox Code Playgroud)

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

sty*_*ane 71

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

>>> width = 20
>>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
              Python :            Very Good
Run Code Online (Sandbox Code Playgroud)

从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'
Run Code Online (Sandbox Code Playgroud)


Fré*_*idi 34

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

print '%*s : %*s' % (20, "Python", 20, "Very Good")
Run Code Online (Sandbox Code Playgroud)

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

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])
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 6

print '%*s : %*s' % (width, 'Python', width, 'Very Good')
Run Code Online (Sandbox Code Playgroud)


Pra*_*rni 6

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

width = 20
py, vg = "Python", "Very Good"
print(f"{py:>{width}s} : {vg:>{width}s}")
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。这正是我想要的。另外一个问题,变量前面的“>”的作用是什么?我见过其他人前面有“0”。有什么意义吗? (2认同)
  • 事实上,我刚刚找到了答案。'>' 和 '<' 分别用于数字的右对齐和左对齐。这是来源:http://cis.bentley.edu/sandbox/wp-content/uploads/Documentation-on-f-strings.pdf (2认同)