1

This is the result when I apply split() against an empty string with default delimiter and with a " " as delimiter in Python.

>>> print(" ".split(" "))
['','']
>>> print(" ".split())
[]

Can somebody please explain?

3
  • 1
    In both Python 2 and Python 3 "".split(" ") returns a list of only one empty string. Please double check your results. Commented Jul 22, 2018 at 18:58
  • 4
    what's unclear with the documentation? Commented Jul 22, 2018 at 18:58
  • 2
    Could not reproduce print "".split(" "). Moreover, it looks like Python 2.x, why do you have Python-3.x tag? Commented Jul 22, 2018 at 18:58

1 Answer 1

1

The documentation on str.split explicitly mentions the different behavior if you split with no argument and when you use ' ' as argument:

str.split(sep=None, maxsplit=-1)

[...]

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns [''].

[...]

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 [].

(Emphasis mine)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.