Why does len("".split(" ")) give 1? python
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping
--
Chapters
00:00 Why Does Len(&Quot;&Quot;.Split(&Quot; &Quot;)) Give 1? Python
00:06 Accepted Answer Score 22
01:04 Answer 2 Score 2
01:19 Answer 3 Score 0
01:27 Answer 4 Score 4
01:44 Thank you
--
Full question
https://stackoverflow.com/questions/1870...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #string
#avk47
ACCEPTED ANSWER
Score 22
str.split(sep) returns at least one element. If sep was not found in the text, that one element is the original, unsplit text.
For an empty string, the sep delimiter will of course never be found, and is specifically called out in the documentation:
Splitting an empty string with a specified separator returns
[''].
You probably are confused by the behaviour of the None delimiter option (the default):
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 aNoneseparator returns[].
(emphasis mine). That makes str.split(None) the exception, not the rule.
ANSWER 2
Score 4
[] has length zero. If a list contains anything in it, anything at all, it will have a length >=1 . In this case, [''] has one element in it: the empty string. So it gives one.
ANSWER 3
Score 2
this might be relevant:
Why are empty strings returned in split() results?
split() is designed to be opposite of join() and:
" ".join([""]) == ""
ANSWER 4
Score 0
It is telling you the length of the list that is produced, not the length of the string.