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

Python:拆分字符串时保留多个分隔符于原片段中

Python拆分字符串并将分隔符保留在对应片段中

问题场景

给定字符串:

st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm'

需要以am或pm作为分隔符拆分字符串,且将这些分隔符保留在对应的原片段中,最终得到:

splitlist = ['Walking happened at 8 am',
             'breakfast happened at 9am',
             'baseball happened at 12 pm',
             'lunch happened at 1pm']

解决方案

常规拆分方法要么丢弃分隔符,要么会把分隔符单独作为列表项返回。这里可以借助Python的re模块,通过两种方式实现需求:

方案一:捕获分组拼接法

先通过正则拆分时捕获分隔符,再将相邻的内容片段与对应分隔符拼接:

import re

st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm'
parts = re.split(r'(am|pm)', st)
# 过滤空项并两两拼接内容与分隔符
splitlist = [''.join(parts[i:i+2]) for i in range(0, len(parts)-1, 2) if parts[i].strip()]

print(splitlist)

方案二:非贪婪匹配提取法

直接用正则匹配包含分隔符的完整片段,代码更简洁:

import re

st = 'Walking happened at 8 am breakfast happened at 9am baseball happened at 12 pm lunch happened at 1pm'
splitlist = re.findall(r'.*?(?:am|pm)', st)

print(splitlist)

方案说明

  • 方案一通过re.split拆分时捕获am/pm,再把内容和分隔符重新组合,同时过滤拆分后可能出现的空字符串。
  • 方案二用re.findall搭配非贪婪模式正则.*?(?:am|pm),匹配任意字符直到遇到am或pm,直接提取包含分隔符的完整片段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:40:39