Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between .split(" ") vs .split() [duplicate]

Tags:

python

split

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.


1 Answers

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', '']
like image 153
paxdiablo Avatar answered Oct 22 '25 05:10

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!