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

Viewed 52165

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.

10 Answers

Turn into words

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

# ['Hello', 'World']

Turn into letters

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

# ['H', 'e', 'l', 'l', 'o']

You definitely don't need quotes inside the parenthesis.

sentence = "bla mla gla dla"
sentence.split()

will give you

['bla', 'mla', 'gla', 'dla']

as a result by default.

If you want to split a word into characters, use the list() method instead:

word = "Easy"
x = list(word)
print(x)
#["w", "o", "r", "d"]

Running Windows 10 from the powershell. ***Python the Hardway ***

I removed the ('') from the split() method. Also, read the study drill #3. It mentions used "from ex25 import *". Only these two changes allowed me to run from the interpreter without a traceback. After changing the import line, it runs as written in the book.

Prior to, in the interpreter (not ex25.py) I had to change line 3 'words = break_words(sentence)' to 'functWords = break_words(sentence)'.

Related