gpt4 book ai didi

python - 如何在 Python 中拆分此字符串?

转载 作者:行者123 更新时间:2023-11-28 20:05:03 25 4
gpt4 key购买 nike

我有一个变量string

string = '''Layer:defaultRenderLayer
Line 1 text goes here
Line 2 text goes here
Line 3 text goes here
Layer:diffuse
Line 1 text goes here
Line 2 text goes here
Line 3 text goes here
Line 4 text goes here
Line 5 text goes here
Layer:outline
Line 1 text goes here
Line 2 text goes here'''

我正在尝试拆分文本 Layer 之前的字符串,如下所示。

string_list = [
'Layer:defaultRenderLayer\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here',
'Layer:diffuse\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here\nLine 4 text goes here\nLine 5 text goes here',
'Layer:outline\nLine 1 text goes here\nLine 2 text goes here'
]

最佳答案

import re
print re.split(r"\n(?=Layer)",x)

您可以在此处使用 lookaheadre 来实现相同的目的。

输出:

['Layer:defaultRenderLayer\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here', 
'Layer:diffuse\nLine 1 text goes here\nLine 2 text goes here\nLine 3 text goes here\nLine 4 text goes here\nLine 5 text goes here',
'Layer:outline\nLine 1 text goes here\nLine 2 text goes here']

或者你也可以使用re.findall

print re.findall(r"\bLayer\b[\s\S]*?(?=\nLayer\b|$)",x

See Demo

关于python - 如何在 Python 中拆分此字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383307/

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