dumm3rjung3
dumm3rjung3

Reputation: 129

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.

Upvotes: 0

Views: 3099

Answers (2)

mgilson
mgilson

Reputation: 309899

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

Upvotes: 4

Nir Alfasi
Nir Alfasi

Reputation: 53525

You have a closing bracket after details[1] which messes up your code.

Upvotes: 1

Related Questions