以元组为参数的新样式格式

Mar*_*her 29 python string formatting

为什么我不能使用元组作为新样式格式化的参数("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.
Run Code Online (Sandbox Code Playgroud)

而这不是:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

即使{!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
Run Code Online (Sandbox Code Playgroud)

虽然它以这种方式工作:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

ick*_*fay 49

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

因为你有时需要传递多个东西进行格式化,并且一直有一个项目创建元组有点笨拙,旧式的方法出现了一个黑客:如果你把它作为一个元组传递,它将使用的内容元组作为格式化的东西.如果你传递的不是元组,它将使用它作为唯一的格式.

新方法不需要这样的方法:因为它是一种方法,它可以采用任意数量的参数.因此,需要将多个要格式化的内容作为单独的参数传递.幸运的是,您可以使用*以下命令将元组解压缩为参数:

print("First item: {:d}, second item: {:d} and third item: {:d}.".format(*tuple))
Run Code Online (Sandbox Code Playgroud)


Vol*_*ity 18

正如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.
Run Code Online (Sandbox Code Playgroud)

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