python - "tuple index out of range"

标签 python indexing

我正在编写一个程序,以表格格式显示有关国家/地区的信息。当我有 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/

相关文章:

indexing - 正确的术语,我应该说指数还是指数?

python - 过滤 SQLAlchemy 关系

swift - 创建没有 tableView 部分的 indexList?

python - 如何获取调用事件的小部件的 ID (Tkinter)

python - Matplotlib 条形图重叠的条形图

arrays - 在 Matlab 中用矩阵索引多维数组

c - strcpy 将一个项目从 dirent 转换为 char[]

javascript - JQuery - $ ('#test ul > li' ).index(2).hide(); - 可能的?

python - 卡住数据库以测试 Django 中的新功能

python - from django.db import utils ImportError 无法导入名称 utils?