作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个变量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)
您可以在此处使用 lookahead
和 re
来实现相同的目的。
输出:
['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
关于python - 如何在 Python 中拆分此字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33383307/
我是一名优秀的程序员,十分优秀!