简体   繁体   中英

Format string in python with variable formatting

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?

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)

Since python 3.6 you can use f-strings resulting in more terse implementation:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM