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

Python移除字符串后缀'ness'功能代码报错求助:IndexError索引越界问题排查

问题排查与代码修正

咱们先拆解你遇到的IndexError根源,再一步步把代码改对:

核心错误分析

  1. 变量名冲突+错误的遍历逻辑
    你的函数参数命名为word,但实际传入的是一个单词列表。更关键的是,列表推导式[word[:-4] for word in word]有致命问题:

    • 内层循环的word会直接覆盖外层的参数变量名,导致逻辑彻底混乱;
    • 如果测试时传入单个字符串(比如某一个单词),你其实是在遍历字符串的每个字符——每个字符长度只有1,执行[:-4]必然触发索引越界,这就是你看到IndexError的直接原因。
  2. 冗余的循环操作
    你先通过列表推导式生成no_suffix,再用for循环逐个修改,完全可以把逻辑合并到一次遍历里,代码会更简洁高效。

修正后的代码

def remove_suffix_ness(words):
    processed_words = []
    for word in words:
        # 先移除'ness'后缀
        stripped_word = word[:-4]
        # 检查结尾是否为'i',是则替换成'y'
        if stripped_word.endswith('i'):
            processed_words.append(stripped_word[:-1] + 'y')
        else:
            processed_words.append(stripped_word)
    # 把处理后的列表拼接成预期格式的字符串
    return ', '.join(processed_words)

如果喜欢更简洁的写法,也可以用列表推导式一步完成:

def remove_suffix_ness(words):
    return ', '.join(
        word[:-5] + 'y' if word[:-4].endswith('i') else word[:-4]
        for word in words
    )

测试验证

用你给出的输入测试:

input_words = ['heaviness', 'sadness', 'softness', 'crabbiness', 'lightness', 'artiness', 'edginess']
print(remove_suffix_ness(input_words))

输出结果完全符合预期:

heavy, sad, soft, crabby, light, arty, edgy

额外优化(可选)

如果要兼容可能不含ness后缀的单词,可以加一层判断避免错误:

def remove_suffix_ness(words):
    processed_words = []
    for word in words:
        if word.endswith('ness'):
            stripped_word = word[:-4]
            processed_words.append(stripped_word[:-1] + 'y' if stripped_word.endswith('i') else stripped_word)
        else:
            # 不含后缀的单词直接保留
            processed_words.append(word)
    return ', '.join(processed_words)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:27:39