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

如何匹配列表中的指定字符串并将其从输入字符串中删除

问题解决方法

原代码错误原因

  • 不能直接将整个列表words和输入字符串做in包含判断,该语法只能判断单个字符串是否存在于另一个字符串中
  • str.replace()方法要求传入的待替换内容为字符串类型,不能直接传入列表参数
  • 未处理匹配优先级:如果短词组先被替换,会导致更长的组合词组无法被正常识别匹配

修正后代码

words = ["youtube","search youtube","play music"]
inp = "search youtube Rockstar"

# 按词组长度降序排列,优先匹配更长的目标词组
for target_word in sorted(words, key=lambda x: len(x), reverse=True):
    if target_word in inp:
        # 替换后去除首尾多余空格
        inp = inp.replace(target_word, "").strip()

print(inp) # 输出结果为 Rockstar

实现效果说明

运行上述代码后,inp变量的值会变为预期的"Rockstar",满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:09:03