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

Python报TypeError: string indices must be integers错误如何解决

问题原因

你的代码出错的核心是遍历逻辑不对:
for i in options直接遍历列表时,i拿到的是options里的元素本身,也就是"option 1"、"option 2"这类字符串,不是你预期的整数下标。用字符串作为索引去取choices和options的元素,自然会触发类型错误,因为字符串和列表的索引都要求是整数。

修正方案

方案1:用enumerate同时获取索引和元素(推荐写法)

alphabet = 'abcdefghijklmnopqrstuvwxyz'
options = ["option 1", "option 2", "option 3", "option 4"]
choices = alphabet[0:len(options)]

for idx, option in enumerate(options):
    print(choices[idx], option)

方案2:遍历索引范围

如果你需要严格按下标访问,也可以遍历和列表长度一致的整数范围:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
options = ["option 1", "option 2", "option 3", "option 4"]
choices = alphabet[0:len(options)]

for i in range(len(options)):
    print(choices[i], options[i])

两种方案运行后都能得到你期望的输出:

a option 1
b option 2
c option 3
d option 4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:54:01