10

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?

Manuel Ebert
  • 8,429
  • 4
  • 40
  • 61

2 Answers2

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)
Manuel Ebert
  • 8,429
  • 4
  • 40
  • 61
  • 2
    Yes, this is one of the reasons that `.format()` is preferred to `%` format strings – John La Rooy May 08 '12 at 12:41
  • 1
    Afaik `%` is considered deprecated and will be removed in future versions of Python 3, although no actual deadline has been announced yet. – Manuel Ebert May 08 '12 at 13:46
  • 2
    The word to search for in [the docs](https://docs.python.org/2/library/string.html) is "nesting" which is hard to remember when you don't already know the answer ;) – hobs Dec 30 '15 at 00:03
  • @ManuelEbert It [has will be deprecated](https://stackoverflow.com/q/13451989/974555) but I'd say it's very unlikely to be removed in our lifetimes as the cost of removing it is large and the benefit is small. – gerrit Oct 25 '18 at 10:04
0

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
>>> 
Petr Vepřek
  • 1,547
  • 2
  • 24
  • 35