Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does len("".split(" ")) give 1? python

Tags:

python

string

What is the pythonic explanation for len("".split(" ")) == 1 showing True?

Why does the "".split("") yield ['']

>>> len("".split(" "))
1
>>> "".split(" ")
['']
like image 329
alvas Avatar asked Sep 09 '13 15:09

alvas


People also ask

What is 1 .split Python?

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.

What does .split return in Python?

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.

How does LEN () work in Python?

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.


3 Answers

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 a None separator returns [].

(emphasis mine). That makes str.split(None) the exception, not the rule.

like image 88
Martijn Pieters Avatar answered Sep 30 '22 14:09

Martijn Pieters


[] 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.

like image 27
Hrishi Avatar answered Sep 30 '22 15:09

Hrishi


this might be relevant:

Why are empty strings returned in split() results?

split() is designed to be opposite of join() and:

" ".join([""]) == ""
like image 20
fsw Avatar answered Sep 30 '22 13:09

fsw