[英]How to print out print out only elements of a list containing certain letters?
I am working on a project and I want to write a code, that would find words containing only certain letters in a sentence and then return them (print them out). 我正在一个项目上,我想编写一个代码,该代码将查找句子中仅包含某些字母的单词,然后将其返回(打印出来)。
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)
Now the part I am struggeling with is, how do I append only words containig letter "a" for example? 现在,我正在苦苦挣扎的部分是,例如,如何仅附加包含字母“ a”的单词?
you can act like this: 您可以这样操作:
words = sentence.split()
lst = [word for word in words if 'a' in word]
print(lst)
# ['am', 'asking', 'a', 'Stack']
Try this! 尝试这个! I hope it's well understood!
我希望它是很好的理解!
sentence = "I am asking a question on Stack Overflow"
lst = []
change = sentence.split()
#we are going to check in every word of the sentence, if letter 'a' is in it.
for a in change:
if 'a' in a:
print(a+" has an a! ")
lst.append(a)
print(lst)
This will output: 这将输出:
['am', 'asking', 'a', 'Stack']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.