如何修改Python后缀移除函数,仅处理长度小于8的字符串?
修改Python函数实现仅对长度小于8的单词移除指定后缀
原函数代码
def removeSuffixs(sentence): line = sentence.split() new_line = [] string_index_list = [] string_length_list = [] suffix_list = ['ed', 'ly', 'ing'] for i in line: string_index = line.index(i) string_index_list.append(string_index) string_length = len(line[string_index]) string_length_list.append(string_length) for x in line: for suff in suffix_list: for s in string_length_list: if x.endswith(suff) and s < 8: x = x.removesuffix(suff) else: pass new_line.append(x) new_line2 = ' '.join(new_line) return new_line2 print(removeSuffixs('a boy is jumping quickly tremendously'))
当前输出
a boy is jump quick tremendous
需求目标
添加条件,仅对长度小于8的字符串移除后缀,使输出变为:
a boy is jump quick tremendously
修改后的函数代码
def removeSuffixs(sentence): line = sentence.split() new_line = [] suffix_list = ['ed', 'ly', 'ing'] for word in line: # 获取当前单词的长度,直接做判断 word_len = len(word) for suff in suffix_list: if word.endswith(suff) and word_len < 8: word = word.removesuffix(suff) # 找到匹配的后缀就停止遍历,避免重复移除 break new_line.append(word) return ' '.join(new_line) print(removeSuffixs('a boy is jumping quickly tremendously'))
修改说明
- 删掉了冗余的
string_index_list和string_length_list,处理每个单词时直接获取自身长度即可,无需额外存储 - 每个单词仅判断自身长度是否小于8,解决了原代码中循环所有长度导致的错误判断问题
- 添加
break语句,找到匹配后缀后立即停止遍历后缀列表,避免对同一单词多次移除后缀 - 简化结果拼接逻辑,最后统一用
join生成结果,无需在循环内反复拼接
内容的提问来源于stack exchange,提问作者Ken Lo
相关产品推荐
相关产品推荐

