python - 如何打印出仅包含某些字母的列表元素?
问题描述
我正在做一个项目,我想编写一个代码,它会在句子中找到仅包含某些字母的单词,然后将它们返回(打印出来)。
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”的单词?
解决方案
你可以这样做:
words = sentence.split()
lst = [word for word in words if 'a' in word]
print(lst)
# ['am', 'asking', 'a', 'Stack']
推荐阅读
- google-cloud-platform - Filebeat 负载平衡不起作用
- spring-boot - Spring Boot 集成测试 Jersey JAX-RS 资源
- html - 将段落与 FontAwesome 图标对齐
- c - 从LabVIEW数组中获取内存地址
- php - 如何覆盖两个相同的特征方法?
- python - 我如何部署电报机器人?
- css - 将鼠标悬停在卡片上的任何内容上时如何更改文本颜色?
- javascript - 启用/禁用按钮取决于两个输入
- reactjs - How to pass state value from one class to another in Reactjs
- java - 在更改意图之前提示相机许可