Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.split(' ') giving me "ValueError: empty separator" for a sentence in the form of a string

TLDR: If you don't specify a character for str.split to split by, it defaults to a space or tab character. My error was due to the fact that I did not have a space between my quotes.


In case you were wondering, the separator I specified is a space:

words = stuff.split(" ")

The string in question is This is an example of a question. I also tried # as the separator and put #'s into my sentence and got the same error.

Edit: Here is the complete block

def break_words(stuff):
"""This function will break up words for us."""
    words = stuff.split(" ")
    return words
sentence = "This is an example of a sentence."
print break_words(sentence)

When I run this as py file, it works. but when I run the interpreter, import the module, and type: sentence = "This is an example of a sentence." followed by print break_words(sentence)

I get the above mentioned error.

And yes, I realise that this is redundant, I'm just playing with functions.

Edit 2: Here is the entire traceback:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "ex25.py", line 6, in break_words
words = stuff.split(' ')

Edit 3: Well, I don't know what I did differently, but when I tried it again now, it worked:

>>> s = "sdfd dfdf ffff"
>>> ex25.break_words(s)
['sdfd', 'dfdf', 'ffff']
>>> words = ex25.break_words(s)
>>>

As you can see, no errors.

like image 536
Glubbdrubb Avatar asked Dec 29 '13 15:12

Glubbdrubb


3 Answers

I had the same issue on this exercise from Learn Python the Hard Way. I just had to put a space between the quote marks.

def break_words(stuff):
    """this function will break up words."""
    words = stuff.split(" ")
    return words

also, as someone mentioned, you have to reload the module. Although in this example, since I was using a command prompt on Windows, I had to exit() then restart my py session and import the exercise again.

like image 184
Matthew Avatar answered Nov 16 '22 04:11

Matthew


As the REPL output below shows, this error is generated by passing an empty string to str.split()

>>> s = "abc def ghi jkl"
>>> s.split(" ")
['abc', 'def', 'ghi', 'jkl']
>>> s.split("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> 

Your code must be passing an empty value to split. Fix this and the error will go away.

like image 33
Vorsprung Avatar answered Nov 16 '22 05:11

Vorsprung


Turn into words

text = 'Hello World'
print(text.split())

# ['Hello', 'World']

Turn into letters

word = 'Hello'
print(list(word))

# ['H', 'e', 'l', 'l', 'o']
like image 3
Flat Dat Avatar answered Nov 16 '22 05:11

Flat Dat