ValueError: empty separator in Python

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

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.

main.py
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.

main.py
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.

main.py
my_str = 'hello world' result = my_str.split(' ') # 👇️ ['hello', 'world'] print(result)

The str.split() method splits the string into a list of substrings using a delimiter.

main.py
my_str = 'apple,banana,kiwi' result = my_str.split(',') # 👇️ ['apple', 'banana', 'kiwi'] print(result)

The method takes the following 2 parameters:

NameDescription
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.

main.py
my_str = 'hello world' result = my_str.split('!') # 👇️ ['hello world'] print(result)

Conclusion #

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(' ').

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.