use*_*069 3 python format tuples
使用.format()with 文本填充时,我遇到了这个错误。
我拥有的:
tuple = ('a', 'b', 'c')
text = "Hi {} hello {} ola {}"
#command I tried to run
text.format(tuple)
Run Code Online (Sandbox Code Playgroud)
我的目标输出:
Hi a hello b ola c
Run Code Online (Sandbox Code Playgroud)
我得到的错误:
IndexError:元组索引超出范围
不知道如何解决这个问题!
您想使用可迭代的解包:
>>> t = (1, 2, 3)
>>> "{}, {}, {}".format(*t)
'1, 2, 3'
Run Code Online (Sandbox Code Playgroud)
旁注:不要tuple用作变量名,因为它是保留的Python 内置函数(即tuple([1, 2, 3]))。