Solve - ValueError: empty separator in Python


Borislav Hadzhiev

Sun Apr 24 20221 min read

Solve - ValueError: empty separator in Python #

The Python "ValueError: empty separator" occurs when we pass an empty string to the str.split() method. To solve the error, use the list() class if you need to get a list of characters, or pass a separator to the str.split() method, e.g. str.split(' ').

valueerror empty separator

Here is an example of how the error occurs.
my_str = 'hello world' result = my_str.split("") # ⛔️ ValueError: empty separator print(result)

We passed an empty string as the separator to the split() method which caused the error.

If you need to get a list containing the characters of the string, use the list() class.
my_str = 'hello world' result = list(my_str) # 👇️ ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] print(result)

The list() class splits the string on each character without a separator.

If you meant to split the string on each space, pass a string containing a space to the str.split() method.
my_str = 'hello world' result = my_str.split(' ') # 👇️ ['hello', 'world'] print(result)

The str.split() method splits the original string into a list of substrings using a delimiter.
my_str = 'apple,banana,kiwi' result = my_str.split(',') # 👇️ ['apple', 'banana', 'kiwi'] print(result)

The method takes the following 2 parameters:

separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If the separator is not found in the string, a list containing only 1 element is returned.
my_str = 'hello world' result = my_str.split('!') # 👇️ ['hello world'] print(result)
Use the search field on my Home Page to filter through my more than 1,000 articles.