2016-08-01 152 views
1

我需要一个字符串'列表'作为输入并相应地格式化它。下面是一些例子输入:拆分整数字符串

string = "This is the input:1. A list element;2. Another element;3. And another one."

而且我想输出是采用以下格式的列表:

list " ["This is the input:", "A list element;", "Another element;", "And another one."]

我曾尝试做如下:

list = string.split('(\d+). ')

希望它会分裂所有整数,然后是完整的sto p和空格,但这似乎不起作用:只返回单个元素列表,表示没有找到任何拆分条件。

有人看到我在做什么错了吗?

+0

alecxe已经回答了如何去做;你在做错的是a)在正则表达式中''string.split()'不带正则表达式,只有文本文本和b)'.'是一个特殊字符,可以匹配任何东西,所以一个数字后跟一个* dot *需要'.'用反斜杠转义。 – TessellatingHeckler

+0

感谢您的输入 - 踢自己不逃避''。但它有点让人欣慰,知道它不会''d''无论如何。 –

回答

2

可以使用re.split() method的开裂:;后面跟着一个或多个数字后面跟着一个点和一个空格:

>>> re.split(r"[:;]\d+\.\s", s) 
['This is the input', 'A list element', 'Another element', 'And another one.'] 

为了保持:;劈叉里面,你可以使用一个positive lookbehind check

>>> re.split(r"(?<=:|;)\d+\.\s", s) 
['This is the input:', 'A list element;', 'Another element;', 'And another one.']