【问题标题】:Format string in python with variable formatting使用变量格式在python中格式化字符串
【发布时间】:2012-05-08 12:16:30
【问题描述】:

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

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

但是看起来很笨拙。难道没有更好的办法来处理这种情况吗?

【问题讨论】:

    标签: python string string-formatting


    【解决方案1】:

    好的,问题已经解决了,下面是答案,供日后参考:变量可以嵌套,所以效果很好:

    for item, qty in cart.items():
        print "{0:{1}} - {2}".format(item, column_width, qty)
    

    【讨论】:

    • 是的,这就是.format()优于%格式化字符串的原因之一
    • Afaik % 已被视为已弃用,并将在 Python 3 的未来版本中删除,但尚未宣布实际截止日期。
    • the docs 中搜索的词是“嵌套”,当您还不知道答案时很难记住它;)
    • @ManuelEbert It has will be deprecated 但我想说它在我们有生之年被移除的可能性很小,因为移除它的成本很高,而收益却很小。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      相关资源
      最近更新 更多