【问题标题】:New style formatting with tuple as argument以元组为参数的新样式格式
【发布时间】:2017-02-12 14:53:29
【问题描述】:

为什么我不能使用元组作为新样式格式化程序的参数(“string”.format())?它在旧样式中工作正常(“字符串”%)?

此代码有效:

>>> tuple = (500000, 500, 5)
... print "First item: %d, second item: %d and third item: %d." % tuple

    First item: 500000, second item: 500 and third item: 5.

这不是:

>>> tuple = (500000, 500, 5)
... print("First item: {:d}, second item: {:d} and third item: {:d}."
...       .format(tuple))

    Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
    ValueError: Unknown format code 'd' for object of type 'str'

即使使用 {!r}

>>> tuple = (500000, 500, 5)
... print("First item: {!r}, second item: {!r} and third item: {!r}."
...       .format(tuple))

    Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
    IndexError: tuple index out of range

虽然它以这种方式工作:

>>> print("First item: {!r}, second item: {!r} and third item: {!r}."
...       .format(500000, 500, 50))

    First item: 500000, second item: 500 and third item: 5.

【问题讨论】:

    标签: python string formatting


    【解决方案1】:

    旧的格式化方式使用二元运算符%。就其性质而言,它只能接受两个参数。新的格式化方式使用一种方法。方法可以接受任意数量的参数。

    由于您有时需要将多个内容传递给格式化,并且始终使用一个项目创建元组有点笨拙,因此旧式方法提出了一个技巧:如果您将其作为元组传递,它将使用元组的内容作为要格式化的东西。如果你传递给它的不是元组,它会使用它作为唯一的格式。

    新方法不需要这样的hack:因为它是一种方法,它可以接受任意数量的参数。因此,需要将多个要格式化的东西作为单独的参数传递。幸运的是,您可以使用 * 将元组解压缩为参数:

    print("First item: {:d}, second item: {:d} and third item: {:d}.".format(*tuple))
    

    【讨论】:

      【解决方案2】:

      正如icktoofay 解释的那样,在旧的格式化风格中,如果你传入一个元组,Python 会自动解压它。

      但是,您不能将元组与 str.format 方法一起使用,因为 Python 认为您只传递了一个参数。您必须使用 * 运算符解压缩元组,才能将每个元素作为单独的参数传递。

      >>> t = (500000, 500, 5)
      >>> "First item: {:d}, second item: {:d} and third item: {:d}.".format(*t)
      First item: 500000, second item: 500 and third item: 5.
      

      另外,您会注意到我将您的 tuple 变量重命名为 t - 不要为变量使用内置名称,因为您会覆盖它们,这可能会导致后续问题。

      【讨论】:

      • @Volatility 我认为 {:d} 没有必要。如果您想要订购数据,您可以简单地使用 {} 或在元组 {0}{1}{2} 中使用索引或数据指定顺序
      • @GeoStoneMarten 虽然我有点同意,但使用 {:d} 更清楚地表明你想要一个十进制数字(供其他人阅读你的代码)
      【解决方案3】:

      实际上可以使用元组作为format() 的参数,如果您手动索引花括号内的元组:

      >>> t = (500000, 500, 5)
      >>> print("First item: {0[0]:d}, second item: {0[1]:d} and third item: {0[2]:d}.".format(t))
      First item: 500000, second item: 500 and third item: 5.
      

      不过,我发现这比 * 方法不太清楚。

      【讨论】:

      • 在简单的情况下,我同意* 解包更清晰,但这种方法也适用于嵌套元组的情况。
      猜你喜欢
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2012-08-04
      • 2011-12-25
      相关资源
      最近更新 更多