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

Python编写字符串处理函数及无法删除end、exit关键词问题求解

问题排查与修复方案

现有代码的问题

  • 条件判断用了elif,如果字符串中同时存在end和exit,只会删除第一个匹配到的exit,不会处理end
  • remove()方法仅能删除列表中第一个匹配的元素,多个相同目标值无法全部删除
  • 没有做大小写兼容,你提到的End因为首字母大写,和匹配条件的小写end不一致,无法被识别删除
  • 没有实现空单词过滤、单词转大写、分号拼接的核心逻辑

修复后的代码

def fun(long_string):
    # 按空格拆分字符串
    word_list = long_string.split(' ')
    result = []
    for word in word_list:
        # 跳过空单词
        if not word:
            continue
        # 转小写后判断是否是要排除的end/exit,不区分大小写
        if word.lower() in ('end', 'exit'):
            continue
        # 符合要求的单词转大写加入结果
        result.append(word.upper())
    # 用分号拼接返回
    return ';'.join(result)

效果验证示例

输入"hello End world exit test ",返回结果为"HELLO;WORLD;TEST"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:54:03