【问题标题】:Python regular expression split() stringPython 正则表达式 split() 字符串
【发布时间】:2012-05-28 16:36:09
【问题描述】:

我对 python 中的正则表达式很陌生。我有以下字符串,想将它们分成五类。我只是使用 split() 但它只会根据空格进行拆分。

s = "1 0 A10B 1/00 Description: This is description with spaces"
sp = s.split()
>>> sp
["1", "0", "A10B", "1/00", "Description:", "This", "is", "description", "with", "spaces"]

如何编写正则表达式使其像这样拆分:

 ["1", "0", "A10B", "1/00", "Description: This is description with spaces"]

有人可以帮忙吗?谢谢!

【问题讨论】:

  • 感谢大家的回复!

标签: python regex string split


【解决方案1】:

您可以简单地指定拆分数量:

s.split(' ', 4)

【讨论】:

    【解决方案2】:

    split() 的第二个参数是要执行的最大拆分次数。如果将此设置为 4,则剩余的字符串将是列表中的第 5 项。

     sp = s.split(' ', 4)
    

    【讨论】:

      【解决方案3】:

      不是一个完美的解决方案。但首先。

      >>> sp=s.split()[0:4]
      >>> sp.append(' '.join(s.split()[4:]))
      >>> print sp
      ['1', '0', 'A10B', '1/00', 'Description: This is description with spaces']
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        • 2020-11-29
        • 2020-05-05
        • 2011-11-28
        • 2021-09-07
        • 2016-01-10
        相关资源
        最近更新 更多