如果我想让我的格式化字符串动态可调,我将更改以下代码
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)
对于那些想使用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)