gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:14 26 4
gpt4 key购买 nike

假设我有字符串:

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>"]

这是期望的输出:

splitString = splitByTags(string, tags)

for s in splitString:
print(s)

输出

"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

例如:

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>

关于python - 使用多个分隔符在 python 中拆分字符串的最佳方法 - 同时保留分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com