-4

I have a list "stopwords" that contains ["apple", "banana", "pear", "'", "\""].

I have another variable that contains a sentence: "sentence".

I want a simple way to be able to check to see if the string "sentence" contains any words in the list "stopwords" and if it does, then throw an error without using a for loop.

Rolando
  • 58,640
  • 98
  • 266
  • 407

2 Answers2

-1
stopwords=["apple", "banana", "pear"]
sentence="sentence"
for item in stopwords:
    if item not in sentence:
        continue
    else:
    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

EDIT:

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")
CyanogenCX
  • 414
  • 6
  • 17
-1

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'
>>> pattern.search(sentence) != None
True

>>> sentence = 'one crabapple each'
>>> pattern.search(sentence) != None
False

>>> sentence = 'ten apples more'
>>> pattern.search(sentence) != None
False

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138