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

时间:2016-02-10 14:19:44

标签: python string

我想检查是否在没有任何循环或迭代的情况下在另一个字符串中找到所有单词:

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

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

all(a in sentence)

应该返回TRUE

2 个答案:

答案 0 :(得分:4)

您可以根据具体需要使用一组,如下所示:

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

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

这将打印True,其中<=issubset

答案 1 :(得分:3)

应该是:

all(x in sentence for x in a)

或者:

>>> 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')