【问题标题】:Putting the words in a string into a list [duplicate]将字符串中的单词放入列表中[重复]
【发布时间】:2020-01-17 09:37:05
【问题描述】:

我是 python 新手,我正在尝试将字符串中的单词放入列表中,但我遇到了麻烦。 它应该是这样的:

输入:sentence = "abcde that i like."

输出:list_of_words = ['abcde', 'that', 'i', 'like.']

这是我尝试过的:

word = "" 
list_of_words = []
sentence = "abcde that i like."
for letter in sentence:
  if letter != " ":
    word += letter 
  else:
    list_of_words.append(word)
    word = ""
print(list_of_words)

当我运行代码时,输​​出是:

['abcde', 'that', 'i']

我正在试图弄清楚为什么最后一个单词没有包含在列表中。

【问题讨论】:

  • 你总是可以使用.split(),嗯。至于为什么不包括最后一个单词,请尝试自己遍历循环的最后几次迭代。
  • 谢谢,我不知道 .split() 的存在非常有用。最后一个词没有附加,因为句子没有以空格结尾,完全没有意识到这一点。我重复了最后几次互动,但由于某种原因,我没有一直走到最后。
  • 您只检查空格,而不是句点或其他标点符号

标签: python string list


【解决方案1】:

你应该简单地使用str.split():

>>> sentence = "abcde that i like."
>>> list_of_words = sentence.split()
>>> list_of_words
['abcde', 'that', 'i', 'like.']

如果您想要没有标点符号的更好结果,例如句点“.”在演示中,你应该尝试正则表达式:

>>> import re
>>> re.findall(r'\w+', sentence)
['abcde', 'that', 'i', 'like']

在此处阅读更多信息:re — Regular expression operations — Python 3.8.1 documentation!

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多