Python复杂分裂函数

2024-06-24 12:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

_list = ['match','regex','find']
_str = 'find the match and then find the regex later on'

根据列表,可以将str拆分为:?你知道吗

['find',' the ','match',' and then ','find',' the ','regex',' later on']

请注意,拆分的字符串为子字符串的其余部分保留空间

干杯


Tags: andthe字符串列表onmatchfindlist
2条回答

使用正则表达式。re.split

例如:

import re

l = ['match','regex','find']
_str = 'find the match and then find the regex later on'

print([i for i in re.split("("+"|".join(l)+ ")", _str) if i])

输出:

['find', ' the ', 'match', ' and then ', 'find', ' the ', 'regex', ' later on']

可以将re.findall与以下正则表达式一起使用:

import re
print([s for m in re.findall(r'(^.*?|)({0})(.*?)(?={0}|$)'.format('|'.join(_list)), _str) for s in m if s])

这将输出:

['find', ' the ', 'match', ' and then ', 'find', ' the ', 'regex', ' later on']

相关问题 更多 >