小编典典

Python-如何将字符串拆分为列表?

python

我希望我的Python函数拆分一个句子(输入)并将每个单词存储在列表中。我当前的代码拆分了句子,但没有将单词存储为列表。我怎么做?

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)
python list split 

阅读 1704

收藏
2020-02-07

共1个答案

小编典典

text.split()

这应该足以将每个单词存储在列表中。 words已经是句子中单词的列表,因此不需要循环。

其次,这可能是拼写错误,但是你的循环有些混乱。如果你确实确实想使用附加,它将是:

words.append(word)

word.append(words)
2020-02-07