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

Python如何删除字符串中第一个匹配词到第二个匹配词间的内容

Python字符串处理:保留第一个匹配词及第二个匹配词后的内容

给定字符串:

x = "India is the country of festivals. India is known for its rich culture. National bird of India is peacock"

指定匹配词 n = "India",需要删除第一个India之后到第二个India出现前的所有内容,最终得到:

"India is known for its rich culture. National bird of India is peacock"

方法一:使用字符串split方法

利用split按匹配词分割字符串,再重新拼接目标部分:

x = "India is the country of festivals. India is known for its rich culture. National bird of India is peacock"
n = "India"

parts = x.split(n)
# 拼接第一个匹配词 + 第二个及之后的所有分段(用匹配词连接)
result = n + n.join(parts[2:])
print(result)

执行后输出即为所需结果。split(n)会将原字符串拆分为包含空字符串的列表,取parts[2:]即可获取第二个匹配词之后的所有内容,再用n连接后拼在第一个n后面。

方法二:使用正则表达式

通过正则匹配并替换第一个匹配词到第二个匹配词之间的内容:

import re

x = "India is the country of festivals. India is known for its rich culture. National bird of India is peacock"
n = "India"

# 构建正则模式,转义匹配词避免特殊字符干扰
pattern = re.compile(re.escape(n) + r"(.*?)" + re.escape(n))
# 仅替换第一次匹配的内容,将中间部分替换为匹配词本身
result = pattern.sub(n, x, count=1)
print(result)

re.escape(n)确保匹配词中的特殊字符被正确解析,(.*?)采用非贪婪匹配捕获中间内容,count=1限制只处理第一组匹配,最终实现保留第一个匹配词并接上第二个匹配词及后续内容的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:20:53