动态格式化字符串 [英] Format string dynamically

查看:79
本文介绍了动态格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想让我的格式化字符串动态可调,我可以从

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

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

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?

推荐答案

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

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

这篇关于动态格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆