How to split a string into a list?

0 votes

I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far 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)

Jul 30, 2018 in Python by bug_seeker
• 15,350 points
59 views

1 answer to this question.

0 votes

You can use the function 

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)

Hope this helps @bug_seeker

answered Jul 30, 2018 by Priyaj
• 56,580 points

Related Questions In Python

0 votes
1 answer

Split a string into a list of characters

This is easy. Just use the list() ...READ MORE

answered Jun 19, 2018 in Python by Hamartia's Mask
• 1,580 points
28 views
0 votes
1 answer
0 votes
1 answer

How to perform string operations on every element of a list of strings?

This can be done using list comprehension ...READ MORE

answered Jul 18 in Python by Arvind
• 2,960 points
21 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 272 views
+4 votes
6 answers
0 votes
1 answer

How to split a string to array in Python?

This way you can split your string ...READ MORE

answered Mar 4 in Python by Priyaj
• 56,580 points
71 views
0 votes
1 answer

How to sort a list of strings?

Try  items = ["live", "like", "code", "cool", "bug"] ...READ MORE

answered Jul 27, 2018 in Python by Priyaj
• 56,580 points
25 views