简体   繁体   中英

Python - “tuple index out of range”

I am writing a program to display information about countries in a table format. It worked perfectly fine when I had 3 countries, but changing it to 10 (and adjusting all necessary code accordingly) resulted in the error, "Tuple index out of range" in the line:

print("{0:^20}{1:^20}{2:^20}{3:^20}{4:^20}{5:^20}[6:^20}{7:^20}{8:^20}{9:^20}".format(newcountrylist[i].country,newcountrylist[i].currency,newcountrylist[i].exchange))

You need to pass in a matching number of arguments for your format slots. Your format string has 10 slots, but you are only passing in 3 values.

Reduced to 4 format slots, with only 3 arguments to .format() , shows the same error:

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

When I passed in 4 arguments the .format() call succeeds.

As an aswer to jon141: I'm also facing this issue and I'm trying to solve this by looping over one item of a column (I'm passing a 2 dimensional array) and then building the string based on that. So I end up with a string like

template="{0!s:10}{1!s:15}...{n!s:24}

The elements I want to format I put in a tuple. but when I do

template.format(tuple_variable)

it throws an error that the tuple index is out of range

Probably because it's now passing a tuple of a tuple to the function, which has one element, the tuple

I haven't figured out how to fix that yet, but follow the thread if you need more info on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM