How to split a string into a list?

后端 未结 9 2488
执念已碎
执念已碎 2020-11-21 04:32

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

相关标签:
9条回答
  • 2020-11-21 05:23

    I want my python function to split a sentence (input) and store each word in a list

    The str().split() method does this, it takes a string, splits it into a list:

    >>> the_string = "this is a sentence"
    >>> words = the_string.split(" ")
    >>> print(words)
    ['this', 'is', 'a', 'sentence']
    >>> type(words)
    <type 'list'> # or <class 'list'> in Python 3.0
    

    The problem you're having is because of a typo, you wrote print(words) instead of print(word):

    Renaming the word variable to current_word, this is what you had:

    def split_line(text):
        words = text.split()
        for current_word in words:
            print(words)
    

    ..when you should have done:

    def split_line(text):
        words = text.split()
        for current_word in words:
            print(current_word)
    

    If for some reason you want to manually construct a list in the for loop, you would use the list append() method, perhaps because you want to lower-case all words (for example):

    my_list = [] # make empty list
    for current_word in words:
        my_list.append(current_word.lower())
    

    Or more a bit neater, using a list-comprehension:

    my_list = [current_word.lower() for current_word in words]
    
    0 讨论(0)
  • 2020-11-21 05:24
    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)
    
    0 讨论(0)
  • 2020-11-21 05:25

    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']
    >>> 
    
    0 讨论(0)
提交回复
热议问题