我正在编写一个程序,以表格格式显示有关国家/地区的信息。当我有 3 个国家时它工作得很好,但是将它更改为 10(并相应地调整所有必要的代码)导致错误,行中的“元组索引超出范围”:
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))
最佳答案
您需要为您的格式槽传递匹配数量的参数。您的格式字符串有 10 个槽,但您只传递了 3 个值。
减少到 4 个格式槽,.format()
只有 3 个参数,显示相同的错误:
>>> '{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 '
当我传入 4 个参数时,.format()
调用成功。
关于 python - "tuple index out of range",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13903427/