使用变量格式在python中格式化字符串 [英] Format string in python with variable formatting
本文介绍了使用变量格式在python中格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用变量来格式化我的变量?
How can I use variables to format my variables?
cart = {"pinapple": 1, "towel": 4, "lube": 1}
column_width = max(len(item) for item in items)
for item, qty in cart.items():
print "{:column_width}: {}".format(item, qty)
> ValueError: Invalid conversion specification
或
(...):
print "{:"+str(column_width)+"}: {}".format(item, qty)
> ValueError: Single '}' encountered in format string
不过,我能做的是首先构造格式化字符串,然后对其进行格式化:
What I can do, though, is first construct the formatting string and then format it:
(...):
formatter = "{:"+str(column_width)+"}: {}"
print formatter.format(item, qty)
> lube : 1
> towel : 4
> pinapple: 1
不过看起来很笨拙.难道没有更好的方法来处理这种情况吗?
Looks clumsy, however. Isn't there a better way to handle this kind of situation?
推荐答案
好的,问题已经解决了,这里是供以后参考的答案:变量可以嵌套,所以这很好用:
Okay, problem solved already, here's the answer for future reference: variables can be nested, so this works perfectly fine:
for item, qty in cart.items():
print "{0:{1}} - {2}".format(item, column_width, qty)
这篇关于使用变量格式在python中格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文