You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用input获取的索引访问列表报TypeError如何解决?

报错原因

Python 中input()函数的返回值默认是字符串类型,你代码中获取的索引变量g是字符串,而Python列表仅支持整数或切片作为索引,因此触发TypeError类型错误。

修复方法

将用户输入的索引值转换为整数类型即可解决问题,核心修改点是将获取索引的代码改为:

g = int(input('enter the index of the word to display:  '))

优化后完整代码(添加异常处理,避免非法输入导致程序崩溃)

print("<<== program to select and display words of an user input string ==>>")
s = input("enter a string:   ")
split1 = s.split()
len1 = len(split1)
header1 = "----------------------------------------------"
heading = "printing words and their indexes"
print(header1)
print(heading.center(45))
print(header1)
for x in range(len1):
     print("        ", x, "---->", split1[x])
print(header1)
print('\n'*2)

try:
    # 转换输入为整数
    g = int(input('enter the index of the word to display:  '))
    # 判断索引是否在合法区间
    if 0 <= g < len(split1):
        print(split1[g])
    else:
        print(f"输入索引不合法,合法索引范围为 0 ~ {len(split1)-1}")
except ValueError:
    print("请输入有效的整数索引")

内容的提问来源于stack exchange,提问作者potato_noodles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:18:03