【问题标题】:Is there a difference between .split(" ") vs .split() [duplicate].split(" ") 与 .split() 之间是否有区别 [重复]
【发布时间】:2020-09-12 17:51:35
【问题描述】:

.split(' ').split() 在 python 中是否有根本区别? 我相信.split() 的默认值是空格,所以两者应该是相同的,但我在hackerrank 上得到不同的结果。

【问题讨论】:

标签: python split


【解决方案1】:

根据docs(针对 Python 3.8,我强调):

如果未指定sepNone,则应用不同的分割算法:连续空格的运行 被视为单个分隔符,如果字符串有前导或尾随空格,则结果将在开头或结尾不包含空字符串。

所以,不,它们不是一回事。例如(注意AB 之间有两个 空格,开头和结尾各有一个):

>>> s = " A  B "
>>> s.split()
['A', 'B']
>>> s.split(" ")
['', 'A', '', 'B', '']

此外,连续的空白意味着任何个空白字符,而不仅仅是空格:

>>> s = " A\t  \t\n\rB "
>>> s.split()
['A', 'B']
>>> s.split(" ")
['', 'A\t', '', '\t\n\rB', '']

【讨论】:

    【解决方案2】:

    here 的文档 str.split(sep=None, maxsplit=-1)。注意:

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

    >>> a = " hello world "
    >>> a.split(" ")
    ['', 'hello', 'world', '']
    >>> a.split()
    ['hello', 'world']
    
    >>> b = "hello           world"
    >>> b.split(" ")
    ['hello', '', '', '', '', '', '', '', '', '', '', 'world']
    >>> b.split()
    ['hello', 'world']
    
    >>> c = "       "
    >>> c.split(" ")
    ['', '', '', '', '', '', '', '']
    >>> c.split()
    []
    

    【讨论】:

      【解决方案3】:
      >>> print ''.split.__doc__
      S.split([sep [,maxsplit]]) -> list of strings
      
      Return a list of the words in the string S, using sep as the
      delimiter string.  If maxsplit is given, at most maxsplit
      splits are done. If sep is not specified or is None, any
      whitespace string is a separator and empty strings are removed
      from the result.
      

      【讨论】:

        【解决方案4】:

        正如documentation中明确提到的:

        如果sep未指定或为None,则进行不同的拆分 应用算法:连续空白的运行被视为 单个分隔符,结果将不包含空字符串 如果字符串有前导或尾随空格,则开始或结束。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-12
          • 1970-01-01
          • 1970-01-01
          • 2011-04-08
          • 1970-01-01
          • 1970-01-01
          • 2023-03-16
          • 1970-01-01
          相关资源
          最近更新 更多