0

Is this a correct behaviour?

>>> ''.split(' ')
['']

Shouldn't it be an empty array? I mean, there are no spaces in an empty string so there is nothing to split, it should be [], no?

When I use a None as separator, it is empty array:

>>> ''.split()
[]
Richard Knop
  • 81,041
  • 149
  • 392
  • 552

2 Answers2

1

I think the doc has already explained this behavior

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

laike9m
  • 18,344
  • 20
  • 107
  • 140
1

Python docs explicitly specify this behavior

Splitting an empty string with a specified separator returns [''].

user3556757
  • 3,469
  • 4
  • 30
  • 70