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

如何使用Python循环遍历多个后缀并移除字符串中存在的指定后缀?

帮你搞定Python移除后缀的问题!

嘿,我来帮你梳理下这段代码里的问题,再给你一个能正常工作的修正方案哈~

先说说你代码里的几个核心问题:

  • 你的test_list里装的是一整个完整的句子字符串,不是拆分好的单词列表,所以你循环遍历的是列表里的这一个字符串,根本没法逐个处理单词的后缀哦。
  • 代码里test_list.word[:-len(suff)]这种写法完全错误:列表对象根本没有word属性,而且就算你拿到了单词,光做切片操作却不把结果存回去,等于啥都没干。
  • 用elif来判断后缀的话,一个单词只会匹配第一个符合的条件,但我们需要让每个单词检查所有可能的后缀,还要注意先处理长度更长的后缀(比如ing是3个字符,比ed/ly长),避免出现误处理的情况。

修正后的完整代码

# 初始化测试列表
test_list = ['Running the boy gladly jumped']
# 打印原始列表
print("The original list : " + str(test_list))

# 初始化后缀,按长度从长到短排序,优先处理长后缀避免逻辑错误
suffixes = ('ing', 'ly', 'ed')

# 处理列表中的每个句子
processed_list = []
for sentence in test_list:
    # 把句子拆分成单个单词
    words = sentence.split()
    processed_words = []
    for word in words:
        # 遍历所有后缀,找到匹配的就截断
        for suff in suffixes:
            if word.endswith(suff):
                # 截断后缀,保留原单词的大小写(比如Running → Runn)
                processed_word = word[:-len(suff)]
                processed_words.append(processed_word)
                break  # 找到匹配的后缀就停止当前单词的后缀检查
        else:
            # 如果没有匹配任何后缀,直接保留原单词
            processed_words.append(word)
    # 把处理后的单词重新拼接成句子
    processed_sentence = ' '.join(processed_words)
    processed_list.append(processed_sentence)

# 打印结果
print("List after removal of suffix elements : " + str(processed_list))

代码运行结果

执行这段代码后,你会得到:

The original list : ['Running the boy gladly jumped']
List after removal of suffix elements : ['Runn the boy glad jump']

完全符合你想要移除ing、ly、ed后缀的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:43:15