Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does split() return more elements than split(" ") on same string?

I am using split() and split(" ") on the same string. But why is split(" ") returning less number of elements than split()? I want to know in what specific input case this would happen.

like image 826
Shivam Rawat Avatar asked Jul 23 '26 18:07

Shivam Rawat


2 Answers

str.split with the None argument (or, no argument) splits on all whitespace characters, and this isn't limited to just the space you type in using your spacebar.

In [457]: text = 'this\nshould\rhelp\tyou\funderstand'

In [458]: text.split()
Out[458]: ['this', 'should', 'help', 'you', 'understand']

In [459]: text.split(' ')
Out[459]: ['this\nshould\rhelp\tyou\x0cunderstand']

List of all whitespace characters that split(None) splits on can be found at All the Whitespace Characters? Is it language independent?

like image 143
cs95 Avatar answered Jul 26 '26 08:07

cs95


If you run the help command on the split() function you'll see this:

split(...) S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

Therefore the difference between the to is that split() without specifing the delimiter will delete the empty strings while the one with the delimiter won't.

like image 29
Levi Moreira Avatar answered Jul 26 '26 07:07

Levi Moreira