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
or
或
(...):
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?
然而,看起来笨手笨脚。有没有更好的办法来处理这种情况?
1 个解决方案
#1
15
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)
#1
15
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)