在python中使用多个分隔符拆分字符串的最佳方法-同时保留分隔符

在python中使用多个分隔符拆分字符串的最佳方法-同时保留分隔符,python,regex,string,split,substring,Python,Regex,String,Split,Substring,假设我有字符串: string = "this is a test string <LW> I want to <NL>split this string<NL> by each tag I have inserted.<AB>" 输出 "this is a test string <LW>" " I want to <NL>" "split this string<NL>" " by each tag I h

假设我有字符串:

string = "this is a test string <LW> I want to <NL>split this string<NL> by each tag I have inserted.<AB>"
输出

"this is a test string <LW>"
" I want to <NL>"
"split this string<NL>"
" by each tag I have inserted.<AB>"
“这是一个测试字符串”
“我想”
“拆分此字符串”
“通过我插入的每个标记。”

所以基本上我想用多个子字符串分割字符串,同时将这些子字符串保持在分割范围内。最快和最有效的方法是什么?我知道我可以使用string.split并简单地将拆分文本附加到每一行,但是我不确定如何使用多个字符串执行此操作。

使用带括号的
re.split

Ex:

import re
string = "this is a test string <LW> I want to <NL>split this string<NL> by each tag I have inserted.<AB>"
tags = ["<LW>", "<NL>", "<AB>"]

splt_str = re.split("(" + "|".join(tags) + ")", string)

for i in range(0, len(splt_str), 2):
    print("".join(splt_str[i:i+2]))
this is a test string <LW>
 I want to <NL>
split this string<NL>
 by each tag I have inserted.<AB>
重新导入
string=“这是一个测试字符串,我想按插入的每个标记拆分该字符串。”
标记=[“”,“”,“”]
splt_str=re.split(“+”|“.join(tags)+”),字符串)
对于范围内的i(0,len(splt_str),2):
打印(“.join(splt_str[i:i+2]))
输出:

import re
string = "this is a test string <LW> I want to <NL>split this string<NL> by each tag I have inserted.<AB>"
tags = ["<LW>", "<NL>", "<AB>"]

splt_str = re.split("(" + "|".join(tags) + ")", string)

for i in range(0, len(splt_str), 2):
    print("".join(splt_str[i:i+2]))
this is a test string <LW>
 I want to <NL>
split this string<NL>
 by each tag I have inserted.<AB>
这是一个测试字符串
我想
分开这根绳子
通过我插入的每个标记。

以下是一些示例:

import re

def split_string(string, tags):
    string_list = []
    start = 0
    for tag in tags:
        tag_index = re.finditer(tag, string)
        for item in tag_index:
            end_tag = item.start() + len(tag)
            string_list.append(string[start:end_tag])
            start = end_tag

    return string_list



data = split_string(string, tags)
输出:

['this is a test string <LW>', ' I want to <NL>', 'split this string<NL>', ' by each tag I have inserted.<AB>']
[“这是一个测试字符串”,“我想”,“拆分此字符串”,“按我插入的每个标记执行”。]

由以下句子解释:“如果模式中使用了捕获括号,则模式中所有组的文本也将作为结果列表的一部分返回”