3

Is there a fundamental difference between .split(' ') vs .split() in python? I believe .split()'s default value is blank space so the two should be the same but i get different results on hackerrank.

Craig
  • 4,605
  • 1
  • 18
  • 28
  • 4
    Remember to check the [docs](https://docs.python.org/3/library/stdtypes.html#str.split) if you're confused by a method's behavior. – user2357112 May 26 '20 at 02:01
  • You have to check the api documentation for split methods for string. https://www.geeksforgeeks.org/python-string-split/ – Danizavtz May 26 '20 at 02:04

4 Answers4

10

As per the docs (for Python 3.8, and with my emphasis):

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

So, no, they are not the same thing. For example (note there are two spaces between A and B and one at the start and end):

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

Additionally, consecutive whitespace means any whitespace characters, not just spaces:

>>> s = " A\t  \t\n\rB "
>>> s.split()
['A', 'B']
>>> s.split(" ")
['', 'A\t', '', '\t\n\rB', '']
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
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.
Catch22
  • 391
  • 2
  • 5
2

Documentation here for str.split(sep=None, maxsplit=-1). Note:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

>>> 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()
[]
felipe
  • 7,324
  • 2
  • 28
  • 37
0

As clearly mentioned in the documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156