Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

python - 如何将字符串拆分为列表?(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.

(我希望我的Python函数拆分一个句子(输入)并将每个单词存储在列表中。)

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)
  ask by Thanx translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.

(words已经是句子中单词的列表,因此不需要循环。)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...