dumm3rjung3 dumm3rjung3 - 5 months ago 51
Python Question

Tuple index out of range in string formatting

I have a tuple:

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


that has six elements (index 0-5).

If I print with string formatting, like this:

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


I get an "IndexError: tuple index out of range" although I only use the index until
4
and have 6 elements in my tuple.

Answer

It looks like you have a parenthesis in the wrong place:

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

So your format statement is getting 4 arguments when it is expecting 5 (because there are 5 "substitution slots {}") so when it tries to get the 5th parameter, it has an IndexError.

You'll get the same thing with "{}".format() for example:

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