Python 3 格式化方法 - 元组索引超出范围

Python 3 format method - tuple index out of range

我在 Python 3.4.2 中的格式化方法有问题。显示以下错误:

Traceback (most recent call last):
  Python Shell, prompt 2, line 3
builtins.IndexError: tuple index out of range

代码:

A = "{0}={1}"
B = ("str", "string")
C = A.format(B)
print (C)

元组包含索引为 0 和 1 的两个字符串,不应显示此错误。

根据 docs,您应该将参数作为位置参数而不是元组传递。如果要使用元组中的值,请使用 * 运算符。

str.format(*args, **kwargs)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

"The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3'

更具体地说,您需要执行以下操作:

A = "{0}={1}"
B = ("str", "string")
C = A.format(*B)
print (C)

A = "{0}={1}"
C = A.format("str", "string")
print (C)

您必须解压元组以使其具有两个参数而不是一个元组:

A = "{0}={1}"
B = ("str", "string")
C = A.format(*B)
print (C)

或者修改您的格式字符串以接受一个参数和一个序列中的两个元素。

A = "{0[0]}={0[1]}"
B = ("str", "string")
C = A.format(B)
print (C)