【问题标题】:Tuple index out of range in string formatting字符串格式中的元组索引超出范围
【发布时间】:2016-06-07 22:45:51
【问题描述】:

我有一个元组:

('ORF eins', '20:15', '21:05', 'soko-donau.html', 'Soko Donau', 'Schöne neue Welt')

有六个元素(索引 0-5)。

如果我用字符串格式打印,像这样:

print("""Entry {}
Title: {}
Station: {}
Start Time: {}
End Time: {}""".format(programID, details[4], details[0], details[1]), details[2])

我得到一个“IndexError: tuple index out of range”,尽管我只在4 之前使用索引并且我的元组中有 6 个元素。

【问题讨论】:

  • @Abstracted 没有更易读的方法来创建多行字符串。如果为文档字符串保留 """ 很重要,您会期望 PEP 8 对此发表评论,除非它在那里而我错过了。

标签: python


【解决方案1】:

你的括号好像放错地方了:

print("""Entry {}
Title: {}
Station: {}
Start Time: {}
End Time: {}""".format(programID, details[4], details[0], details[1]), details[2])
#                                                                   ^

因此,您的格式语句在预期 5 个参数时得到 4 个参数(因为有 5 个“替换槽 {}”),因此当它尝试获取第 5 个参数时,它有一个 IndexError

例如,"{}".format() 会得到相同的结果:

>>> "{}".format()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

【讨论】:

  • 在我发布后几分钟就看到了,当然现在可以正常工作了:D 无论如何谢谢!
【解决方案2】:

details[1] 后面有一个右括号,这会弄乱你的代码。

【讨论】:

    猜你喜欢
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多