【问题标题】:split string by arbitrary number of white spaces按任意数量的空格分割字符串
【发布时间】:2012-10-23 10:09:47
【问题描述】:

我正在尝试找到最 Pythonic 的方式来拆分字符串,例如

“字符串中的一些单词”

成单个单词。 string.split(' ') 工作正常,但它会在列表中返回一堆空白条目。当然我可以迭代列表并删除空格,但我想知道是否有更好的方法?

【问题讨论】:

    标签: python split


    【解决方案1】:

    只需使用my_str.split() 而不使用' '


    更多,你还可以通过指定第二个参数来指示要执行多少次拆分:

    >>> ' 1 2 3 4  '.split(None, 2)
    ['1', '2', '3 4  ']
    >>> ' 1 2 3 4  '.split(None, 1)
    ['1', '2 3 4  ']
    

    【讨论】:

      【解决方案2】:

      怎么样:

      re.split(r'\s+',string)
      

      \s 是任何空格的缩写。所以\s+ 是一个连续的空白。

      【讨论】:

        【解决方案3】:

        使用不带参数的string.split() 或改用re.split(r'\s+', string)

        >>> s = 'some words in a string   with  spaces'
        >>> s.split()
        ['some', 'words', 'in', 'a', 'string', 'with', 'spaces']
        >>> import re; re.split(r'\s+', s)
        ['some', 'words', 'in', 'a', 'string', 'with', 'spaces']
        

        来自docs

        如果sep未指定或为None,则应用不同的拆分算法:连续的空格被视为单个分隔符,如果字符串的开头或结尾不包含空字符串有前导或尾随空格。因此,使用 None 分隔符拆分空字符串或仅包含空格的字符串将返回 []

        【讨论】:

          【解决方案4】:
          >>> a = "some words in a string"
          >>> a.split(" ")
          ['some', 'words', 'in', 'a', 'string']
          

          split 参数不包含在结果中,所以我猜你的字符串有更多的东西。否则,它应该可以工作

          如果您有多个空格,只需使用不带参数的 split()

          >>> a = "some words in a string     "
          >>> a.split()
          ['some', 'words', 'in', 'a', 'string']
          >>> a.split(" ")
          ['some', 'words', 'in', 'a', 'string', '', '', '', '', '']
          

          或者它只会用一个空格来分割一个

          【讨论】:

            【解决方案5】:

            最Pythonic和正确的方法是不指定任何分隔符:

            "some words in a string".split()
            
            # => ['some', 'words', 'in', 'a', 'string']
            

            另请阅读: How can I split by 1 or more occurrences of a delimiter in Python?

            【讨论】:

              【解决方案6】:
              text = "".join([w and w+" " for w in text.split(" ")])
              

              将大空格转换为单个空格

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-10-11
                • 1970-01-01
                • 2011-12-15
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多