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

时间:2015-10-28 05:09:18

标签: python

我有一个变量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'
]

2 个答案:

答案 0 :(得分:6)

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

See Demo

答案 1 :(得分:3)

您需要使用re.split

re.split(r'\s+(?=Layer:)', string)

这会将之前存在的一个或多个空格字符拆分为字符串Layer:。请注意\s将匹配任何类型的空格字符,即垂直(换行符,carrage return )以及水平空格字符(空格,制表符)。

示例:

>>> import re
>>> 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'''
>>> re.split(r'\s+(?=Layer:)', string)
['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']