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

Python中使用for循环遍历字符串字符触发TypeError问题求助

解决Python嵌套循环遍历字符串字符的TypeError问题

原代码与错误信息

原代码:

x = ["abc", "e", "i"]

for i in x:
    for j in x[i]:
        print(x[i][j])

运行后报错:

print(x[i][j])
TypeError: list indices must be integers or slices, not str

错误原因

外层循环for i in x中,i是列表x中的字符串元素(比如"abc"、"e"),而非整数索引。此时x[i]试图用字符串作为列表的索引,违反了列表索引必须是整数或切片的规则,因此触发TypeError。

修正后的代码

方法一:直接遍历元素(推荐)

这种写法更符合Python的遍历习惯,简洁直观:

x = ["abc", "e", "i"]

for s in x:
    for char in s:
        print(char)

方法二:使用索引遍历

如果需要通过索引操作,可按如下方式修改:

x = ["abc", "e", "i"]

for i in range(len(x)):
    current_str = x[i]
    for j in range(len(current_str)):
        print(current_str[j])

运行结果

两种方法运行后都会输出:

a
b
c
e
i

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:40:29