Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python split empty string [duplicate]

Could someone explain this behaviour on python 2.7.8:

Python 2.7.8 (default, Nov 12 2014, 02:03:09)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ''
>>> a.split()
[]
>>> a.split('\n')
['']

split by any white space gives an empty list, but split by new line gives a list with an empty string. WHY?

Thanks

like image 239
WeaselFox Avatar asked Oct 18 '25 11:10

WeaselFox


1 Answers

From python str.split docs (https://docs.python.org/2/library/stdtypes.html#str.split):

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

like image 131
ndpu Avatar answered Oct 21 '25 12:10

ndpu