简体   繁体   English

Python检查字符串是否包含Python中的所有单词

[英]Python check if string contains all words in Python

I want to check if all words are found in another string without any loops or iterations: 我想检查是否在没有任何循环或迭代的另一个字符串中找到了所有单词:

a = ['god', 'this', 'a']

sentence = "this is a god damn sentence in python"

all(a in sentence)

should return TRUE . 应该返回TRUE

You could use a set depending on your exact needs as follows: 您可以根据实际需要使用一组,如下所示:

a = ['god', 'this', 'a']
sentence = "this is a god damn sentence in python"

print set(a) <= set(sentence.split())

This would print True , where <= is issubset . 这将显示True ,其中<= is issubset

It should be: 它应该是:

all(x in sentence for x in a)

Or: 要么:

>>> chk = list(filter(lambda x: x not in sentence, a)) #Python3, for Python2 no need to convert to list
[] #Will return empty if all words from a are in sentence
>>> if not chk:
        print('All words are in sentence')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM