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

Python如何按子串分割字符串并保留该子串?

解决方案

问题场景

输入字符串:

"Potato1 Potato2,,...Potato3|Potato4"

期望输出:

["Potato1 ", "Potato2,,...", "Potato3|", "Potato4"]

使用普通str.split()或基础re.split()处理时,要么丢失"Potato"前缀,要么将其拆为单独元素,无法得到预期结果。

实现代码

借助正则的正向预查可以解决这个问题,代码示例:

import re

input_str = "Potato1 Potato2,,...Potato3|Potato4"
output_list = [item for item in re.split(r'(?=Potato)', input_str) if item]
print(output_list)

原理说明

(?=Potato)是正向预查语法,它会匹配后面紧跟"Potato"的位置,并在该位置执行分割。分割后过滤掉空字符串,剩下的每个元素都会以"Potato"开头,完全符合需求格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:57:01