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,520 points
832 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
• 58,100 points

Related Questions In Python

0 votes
3 answers
0 votes
1 answer

How to convert each list item into string in a column of data frame. ?

Hey, To split a string you can use ...READ MORE

answered Feb 5, 2020 in Python by Roshni
• 10,520 points
876 views
0 votes
1 answer

How to transform a Python string into a list?

Hi, @Roshni, You can use Python <split()> function ...READ MORE

answered Jun 26, 2020 in Python by Gitika
• 65,890 points
594 views
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
660 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,364 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,936 views
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, 2019 in Python by Priyaj
• 58,100 points
4,983 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
• 58,100 points
802 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP