I want my Python function to split a sentence (input) and store each word in a list. My current code splits the sentence, but does not store the words as a list. How do I do that?
def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
shlex has a
.split()
function. It differs fromstr.split()
in that it does not preserve quotes and treats a quoted phrase as a single word:If you want all the chars of a word/sentence in a list, do this:
How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as
we're
.I think you are confused because of a typo.
Replace
print(words)
withprint(word)
inside your loop to have every word printed on a different lineSplits the string in
text
on any consecutive runs of whitespace.Split the string in
text
on delimiter:","
.The words variable will be a
list
and contain the words fromtext
split on the delimiter.This should be enough to store each word in a list.
words
is already a list of the words from the sentence, so there is no need for the loop.Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:
not