【问题标题】:split string on multiple white spaces but not single ones [duplicate]在多个空格但不是单个空格上拆分字符串[重复]
【发布时间】:2025-12-17 17:00:02
【问题描述】:

我想编写一个函数,将字符串拆分为多个空格,而不是单个空格。

例子:

sample_string = "2012.03.04       check everything      status: OK"
split_string = ["2012.03.04", "check everything", "status: OK"]

如何在不使用丑陋的 for 循环的情况下从 sample_stringsplit_string

【问题讨论】:

    标签: python regex


    【解决方案1】:
    >>> import re
    >>> help(re.split)
    Help on function split in module re:
    
    split(pattern, string, maxsplit=0, flags=0)
        Split the source string by the occurrences of the pattern,
        returning a list containing the resulting substrings.  If
        capturing parentheses are used in pattern, then the text of all
        groups in the pattern are also returned as part of the resulting
        list.  If maxsplit is nonzero, at most maxsplit splits occur,
        and the remainder of the string is returned as the final element
        of the list.
    
    >>> re.split(r'\s{2,}', "2012.03.04       check everything      status: OK")
    ['2012.03.04', 'check everything', 'status: OK']
    

    【讨论】:

      【解决方案2】:

      您可以为此使用re.split()。 (test link)。

      代码:

      import re
      
      sample_string = "2012.03.04       check everything      status: OK"
      
      print(re.split("\s{2,}", sample_string))
      

      输出:

      ['2012.03.04', 'check everything', 'status: OK']
      

      【讨论】:

        【解决方案3】:

        regular expressions:

        import re
        
        sample_string = "2012.03.04       check everything      status: OK"
        REGEX = re.compile(r' {2,}')  # Two or more spaces
        re.split(REGEX, sample_string)
        

        会还给你:

        ['2012.03.04', 'check everything', 'status:', 'OK']

        【讨论】:

          【解决方案4】:

          使用 re 包:

          import re
          re.split(r'\s{2,}', sample_string)
          

          输出:

          ['2012.03.04', 'check everything', 'status: OK']
          

          【讨论】:

            最近更新 更多