IndexError:元组索引超出范围--- Python

时间:2018-04-26 18:01:19

标签: python python-3.x

我正在运行一个简单的代码,它将读取json文件,获取输入并生成输出。但在其中一行中,我收到了错误

activities_obj = document.add_paragraph()
activities_obj = helper.format_alignment(activities_obj)
activities = helper.askForChoices(activities, "Choose extracurricular activities")
activity_string = "Beside coop experience, {}. Additionally, {}. {}. Last but not least, {}."
activiy_para = activity_string.format(*activities)

这是代码,最后一行是错误:

activiy_para = activity_string.format(*activities)
IndexError: tuple index out of range

谢谢

1 个答案:

答案 0 :(得分:0)

您没有向activity_string.format(*activities)

传递足够的参数

你需要用4个键传递dict,

Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> activity_string = "Beside coop experience, {}. Additionally, {}. {}. Last but not least, {}."
>>> activities = {'a': '1', 'b': '2', 'c': '3', 'd': '4'}
>>> activity_string.format(*activities)
'Beside coop experience, a. Additionally, b. c. Last but not least, d.'
>>>

如果你没有传递足够的论点怎么办?

Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> activity_string = "Beside coop experience, {}. Additionally, {}. {}. Last but not least, {}."
>>> activities = {'a': '1'}
>>> activity_string.format(*activities)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>>