join and split with empty delimiter

Irv Kalb Irv at furrypants.com
Wed Jul 17 17:02:58 EDT 2019


I have always thought that split and join are opposite functions.  For example, you can use a comma as a delimiter:

>>> myList = ['a', 'b', 'c', 'd', 'e']
>>> myString = ','.join(myList)
>>> print(myString)
a,b,c,d,e

>>> myList = myString.split(',')
>>> print(myList)
['a', 'b', 'c', 'd', 'e']

Works great. But i've found a case where they don't work that way.  If I join the list with the empty string as the delimiter:

>>> myList = ['a', 'b', 'c', 'd']
>>> myString = ''.join(myList)
>>> print(myString)
abcd

That works great.  But attempting to split using the empty string generates an error:

>>> myString.split('')
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    myString.split('')
ValueError: empty separator

I know that this can be accomplished using the list function:

>>> myString = list(myString)
>>> print(myString)
['a', 'b', 'c', 'd']

But my question is:  Is there any good reason why the split function should give an "empty separator" error?  I think the meaning of trying to split a string into a list using the empty string as a delimiter is unambiguous - it should just create a list of single characters strings like the list function does here.  

My guess is that by definition, the split function attempts to separate the string wherever it finds the delimiter between characters, and because in this case its the empty string, it gives an error.  But if it's going to check for the empty string anyway, it could just call the list function and return a list of characters.

Irv


More information about the Python-list mailing list