10

如何使用变量来格式化我的变量?

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

不过,我能做的是首先构造格式化字符串,然后对其进行格式化:

(...):
    formatter = "{:"+str(column_width)+"}: {}"
    print formatter.format(item, qty)

> lube    : 1
> towel   : 4
> pinapple: 1

然而,看起来很笨拙。难道没有更好的方法来处理这种情况吗?

4

2 回答 2

17

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)
于 2012-05-08T12:19:40.233 回答
0

python 3.6开始,您可以使用f-strings来实现更简洁的实现:

>>> things = {"car": 4, "airplane": 1, "house": 2}
>>> width = max(len(thing) for thing in things)
>>> for thing, quantity in things.items():
...     print(f"{thing:{width}} : {quantity}")
... 
car      : 4
airplane : 1
house    : 2
>>> 
于 2020-03-05T09:45:37.710 回答