在整数上拆分字符串

时间:2016-08-01 16:32:51

标签: python regex string list

我需要将字符串'list'作为输入并相应地格式化它。以下是一些示例输入:

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+). ')

希望它会拆分所有整数后跟一个句号和一个空格,但这似乎不起作用:只返回一个元素列表,表明没有找到任何拆分条件。

任何人都能看到我做错了什么?

1 个答案:

答案 0 :(得分: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.']
相关问题