首页 > 解决方案 > 如何打印出仅包含某些字母的列表元素?

问题描述

我正在做一个项目,我想编写一个代码,它会在句子中找到仅包含某些字母的单词,然后将它们返回(打印出来)。

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”的单词?

标签: pythonpython-3.x

解决方案


你可以这样做:

words = sentence.split()
lst = [word for word in words if 'a' in word]
print(lst)
# ['am', 'asking', 'a', 'Stack']

推荐阅读