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. 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)

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)

Splits the string in text on any consecutive runs of whitespace.

words = text.split()      

Split the string in text on delimiter: "," .

words = text.split(",")   

The words variable will be a list and contain the words from text split on the delimiter.


str.split()

Return a list of the words in the string, using sep as the delimiter ... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>> 
链接地址: http://www.djcxy.com/p/24032.html

上一篇: 如何正确使用goto语句

下一篇: 如何将一个字符串分割成一个列表?