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.
As per the docs (for Python 3.8, and with my emphasis):
If
sepis not specified or isNone, 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', '']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With