Format string in python with variable formatting

后端 未结 2 731
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 11:11

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         


        
相关标签:
2条回答
  • 2021-02-14 11:42

    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
    >>> 
    
    0 讨论(0)
  • 2021-02-14 12:00

    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)
    
    0 讨论(0)
提交回复
热议问题