jack jack - 8 days ago 5
Python Question

Confusion with string split method in python

Consider the following example

a= 'Apple'
b = a.split(',')
print(b)


Output is
['Apple']
.

I am not getting why is it returning a list even when there is no
','
character in
Apple


There might be case when we use split method we are expecting more than one element in list but since we are splitting based on separator not present in string, there will be only one element, wouldn't it be better if this mistake is caught during this split method itself

Answer

The behaviour of a.split(',') when no commas are present in a is perfectly consistent with the way it behaves when there are a positive number of commas in a.

a.split(',') says to split string a into a list of substrings that are delimited by ',' in a; the delimiter is not preserved in the substrings.

If 1 comma is found you get 2 substrings in the list, if 2 commas are found you get 3 substrings in the list, and in general, if n commas are found you get n+1 substrings in the list. So if 0 commas are found you get 1 substring in the list.

If you want 0 substrings in the list, then you'll need to supply a string with -1 commas in it. Good luck with that. :)

Comments