【问题标题】:Split a string on an integer在整数上拆分字符串
【发布时间】:2016-12-06 19:52:06
【问题描述】:

我需要将字符串“列表”作为输入并相应地对其进行格式化。这是一些示例输入:

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

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

有人知道我做错了吗?

【问题讨论】:

  • alecxe 已经回答了怎么做;你做错了什么是a)string.split()不接受正则表达式,只接受文字,b)正则表达式中的.是一个匹配任何东西的特殊字符,所以一个数字后跟一个文字点 需要 . 用反斜杠转义。
  • 感谢您的意见 - 为没有逃脱 . 而踢自己,但知道它无论如何都不会与 \d 一起工作,这有点令人欣慰。

标签: python regex string list


【解决方案1】:

您可以使用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.']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 2010-09-08
    相关资源
    最近更新 更多