What is the pythonic explanation for len("".split(" ")) == 1
showing True?
Why does the "".split("")
yield ['']
>>> len("".split(" "))
1
>>> "".split(" ")
['']
Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
The split() method in Python returns a list of the words in the string/line , separated by the delimiter string. This method will return one or more new strings. All substrings are returned in the list datatype.
Python len() Function The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.
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.
[] 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.
this might be relevant:
Why are empty strings returned in split() results?
split() is designed to be opposite of join() and:
" ".join([""]) == ""
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