Format string in python with variable formatting

浪尽此生 提交于 2020-01-01 04:52:04

问题


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:


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)


来源:https://stackoverflow.com/questions/10498434/format-string-in-python-with-variable-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!