我正在一个项目上,我想编写一个代码,该代码将查找句子中仅包含某些字母的单词,然后将其返回(打印出来)。
sentence = "I am asking a question on Stack Overflow"
lst = []
# this gives me a list of all words in a sentence
change = sentence.split()
# NOTE: I know this isn't correct syntax, but that's basically what I want to do.
lst.append(only words containing "a")
print(lst)
现在我正在苦苦挣扎的部分是,例如,如何仅附加包含字母“ a”的单词?
答案 0 :(得分:3)
您可以这样:
words = sentence.split()
lst = [word for word in words if 'a' in word]
print(lst)
# ['am', 'asking', 'a', 'Stack']
答案 1 :(得分:1)
试试看!我希望它能很好理解!
['am', 'asking', 'a', 'Stack']
这将输出:
{{1}}