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

解决Python报错:‘str’ object does not support item assignment

问题修复方案

错误根源

你用wordListFile.readline()只读取了文件的一行内容,导致WORDS是字符串类型而非列表。Python中字符串是不可变对象,无法通过WORDS[i] = ...这种下标赋值的方式修改内容,这就是报错的直接原因。同时你的代码逻辑是想处理每个单词,但当前写法会把一行里的每个字符当成处理对象,完全偏离了需求。

修复后的代码

方法一:逐行读取并处理(可读性强)

# Load the WORDS list from the text file
with open('sevenletterwords.txt') as wordListFile:
    WORDS = []
    for line in wordListFile:
        # 去除换行符并转大写,添加到列表
        processed_word = line.strip().upper()
        # 跳过文件中的空行
        if processed_word:
            WORDS.append(processed_word)

方法二:列表推导式写法(简洁高效)

with open('sevenletterwords.txt') as wordListFile:
    WORDS = [line.strip().upper() for line in wordListFile if line.strip()]

补充说明

如果你的单词文件是每行一个七字母单词,上面的代码就能正确把所有单词加载为大写形式的列表,完全匹配《Python小项目大合集》里的项目需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:01:07