Borislav Hadzhiev
Sun Apr 24 2022·1 min read
Photo by Madison Compton
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(' ')
.
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:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At 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)