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. 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)
Jan 4, 2021 in Python by anonymous
• 10,520 points
679 views

3 answers to this question.

0 votes
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)
answered Jan 4, 2021 by Gitika
• 65,910 points
0 votes

Split a string into a list where each word is a list item:

txt = "welcome to the jungle"

x = txt.split()

print(x)

answered Jan 4, 2021 by Nikita
0 votes

Using For loop

This approach uses for loop to convert each character into a list. Just enclosing the For loop within square brackets [] will split the characters of word into list.

answered Jan 4, 2021 by David Samon

Related Questions In Python

0 votes
1 answer

How to split a string into a list?

You can use the function  text.split() This should be ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,090 points
643 views
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
682 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
457 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,090 points
4,627 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,007 views
0 votes
1 answer
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,910 points
395 views
0 votes
1 answer

How do you split a list into evenly sized chunks?

Here's a generator that yields the chunks ...READ MORE

answered Dec 3, 2020 in Python by Gitika
• 65,910 points
732 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