Reputation: 122092
What is the pythonic explanation for len("".split(" ")) == 1
showing True?
Why does the "".split("")
yield ['']
>>> len("".split(" "))
1
>>> "".split(" ")
['']
Upvotes: 8
Views: 5389
Reputation: 3695
this might be relevant:
Why are empty strings returned in split() results?
split() is designed to be opposite of join() and:
" ".join([""]) == ""
Upvotes: 2
Reputation: 7138
[] 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.
Upvotes: 4
Reputation: 12316
It is telling you the length of the list that is produced, not the length of the string.
Upvotes: 0
Reputation: 1122222
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 aNone
separator returns[]
.
(emphasis mine). That makes str.split(None)
the exception, not the rule.
Upvotes: 22