如何将字符串拆分为列表? [英] How to split a string into a list?
本文介绍了如何将字符串拆分为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的Python函数拆分一个句子(输入)并将每个单词存储在列表中.我当前的代码拆分句子,但不将单词存储为列表.我该怎么办?
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)
推荐答案
text.split()
这足以将每个单词存储在列表中. words
已经是句子中单词的列表,因此不需要循环.
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)
不是
word.append(words)
这篇关于如何将字符串拆分为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文