How to split a string into a list?

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(words)

Answer

text.split()

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:

words.append(word)

not

word.append(words)

以上是 How to split a string into a list? 的全部内容, 来源链接: www.h5w3.com/37714.html

回到顶部