簡體   English   中英

字符串格式中的元組索引超出范圍

[英]Tuple index out of range in string formatting

我有一個元組:

('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:元組索引超出范圍”,盡管我只使用索引直到4並且元組中有6個元素。

您似乎在錯誤的位置加上了括號:

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

因此,您的format語句在預期為5時會得到4個參數(因為有5個“ substitution slot {} ”),因此當它嘗試獲取第5個參數時,它具有IndexError

例如,您將使用"{}".format()獲得相同的結果:

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

您在details[1]之后有一個右括號,使您的代碼混亂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM