10 python tuples string-formatting
简而言之,为什么我会收到以下错误?
>>> yes = True
>>> 'no [{0}] yes [{1}]'.format((" ", "x") if yes else ("x", " "))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
我使用python 2.6.
Bur*_*ing 15
☞索引选项:
当以格式字符串访问参数的项时,您应该使用index来调用该值:
yes = True
print 'no [{0[0]}] yes [{0[1]}]'.format((" ", "x") if yes else ("x", " "))
Run Code Online (Sandbox Code Playgroud)
{0[0]}格式字符串等于(" ", "x")[0]调用tulple的索引
{0[1]}格式字符串等于(" ", "x")[1]调用tulple的索引
☞ *操作员选项:
或者您可以使用*运算符来解压缩参数元组.
yes = True
print 'no [{0}] yes [{1}]'.format(*(" ", "x") if yes else ("x", " "))
Run Code Online (Sandbox Code Playgroud)
当调用*操作,'no [{0}] yes [{1}]'.format(*(" ", "x") if yes else ("x", " "))等于'no [{0}] yes [{1}]'.format(" ", "x")如果if语句True
☞ **操作符选项(当你的var是dict时这是额外的方法):
yes = True
print 'no [{no}] yes [{yes}]'.format(**{"no":" ", "yes":"x"} if yes else {"no":"x", "yes":" "})
Run Code Online (Sandbox Code Playgroud)
使用*运算符,它接受一个可迭代的参数并将每个参数作为函数的位置参数提供:
In [3]: 'no [{0}] yes [{1}]'.format(*(" ", "x") if yes else ("x", " "))
Out[3]: 'no [ ] yes [x]'
Run Code Online (Sandbox Code Playgroud)
这里的问题是你只提供一个参数string.format():一个元组.当你使用{0}和时{1},你指的是传递给的第0个和第1个参数string.format().由于实际上没有第一个参数,因此会出现错误.
@Patrick Collins建议的*运算符可以工作,因为它解包了元组中的参数,将它们转换为单个变量.这就好像你调用了string.format("","x")(或者反之)
@Tony Yang建议的索引选项有效,因为它引用了传递给的一个元组的各个元素format(),而不是试图引用第二个参数.