How to check if string contains any words in list using python?

This question already has an answer here:


Use a regular expression.

import re

stopwords = ["apple", "banana", "pear"]
pattern = re.compile('|'.join(r'\b{}\b'.format(word) for word in stopwords))

>>> sentence = 'one apple for you'
>>> != None

>>> sentence = 'one crabapple each'
>>> != None

>>> sentence = 'ten apples more'
>>> != None

There is some iteration required to set up the pattern, but not when matching the pattern. Note that this re pattern also ensures that the actual word is present by itself, not as a substring of a larger word.

stopwords=["apple", "banana", "pear"]
for item in stopwords:
    if item not in sentence:
    print("error here")

Make sure you understand the difference between pass and continue.

I don't believe there is a way to do it without a for-loop or while loop


Alternatively you can do just

if item in sentence: print("error here")

to save space if you want.

As Anderson Green has pointed out, if you want the program to stop on the error, do

raise Exception("error here")


 ? Checking a string in a list if there is a word in that string
 ? How to check if a string contains an element from a list in Python
 ? Check if list item contains items from another list
 ? Check if a python series contains any string in another list
 ? Python: check if an object is a sequence
 ? Python: check if an object is a sequence
 ? Python: check if an object is a sequence
 ? Python: check if an object is a sequence
 ? Converting all non-numeric to 0 (zero) in Python
 ? Checking if a variable can be unpacked