-1

In the following examples, I am splitting an empty string by a space. However, in the first example I explicitly used a space and in the second example, I didn't. My understanding was that .split() and .split(' ') were equivalent.

Why do these two examples give different outputs?

In [1]: "".split(' ')
Out[1]: ['']

In [2]: "".split()
Out[2]: []
MSeifert
  • 145,886
  • 38
  • 333
  • 352
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
  • 8
    Did you read https://docs.python.org/3/library/stdtypes.html#str.split? It's explained there. – mkrieger1 Jul 19 '18 at 07:46
  • 2
    Possible duplicate of [Source code for str.split?](https://stackoverflow.com/questions/40332743/source-code-for-str-split) – mkrieger1 Jul 19 '18 at 07:49

1 Answers1

5

From the python's 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. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

Sep is the separator. What it says is if we don't pass anything to split, whitespaces are considered as separators, it will apply a different algorithm to split strings and will return us a [] but since you passed a sep, it will not apply this algorithm

Sushant
  • 3,499
  • 3
  • 17
  • 34