If I have a list of words, how can I check if the string does not contain any of the words in the list and effectively?

advertisements

As title says, I have a list of words, Like stopWords = ["the", "and", "with", etc...] and I'm receiving text like "Kill the fox and dog". I want the output like "Kill fox dog" very efficiently and fast. How can I do this (I know I can iterate using a for loop, but thats not very efficient)


The most imporant improvement is to make stopWords a set. This means the lookups will be very fast

stopWords = set(["the", "and", "with", etc...])
" ".join(word for word in msg.split() if word not in stopWords)

If you just want to know if any of the stopWords are in the text

if any(word in stopWords for word in msg.split()):
    ...