Check if list value is in string but not values within other list

I have a list that looks like this:

list = ['for','and','with','be in']

And I have implemented some code that checks to see if the above words are contained within a string:

if any(word in stringVar for word in list):
   \logic

The above works as expected, however, I wan’t to have some phrases excluded from the above as follows:

exc_list = ['for every','for each']

So essentially, I want to change my if statement so that it returns true if and, with and be in are contained within the stringVar OR for is contained within the stringVar but not when it is followed by every or each.

I had originally implemented this:

if any(word in stringVar for word in list) and any(word not in stringVar for word in exc_list):
   \logic

But this will not work as expected if the stringVar is equal to ‘will be in every day for each week’.

To confirm, I want to return true at all times when and, with and be in are contained within the stringVar, even if for each/every is to appear too. The exclusions should only come into effect when for appears within stringVar

Answer

Just use a replaced string, removing all exclusions in the replacement.

That way you know your exclusions aren’t in the string and can just directly check for items you care about.

string = 'will be in every day for each week'
lst = ['for','and','with','be in']
exclusions = ['for every','for each']

replaced_string = string
for phrase in exclusions:
    replaced_string = replaced_string.replace(phrase, '')
if any(word in replaced_string for word in lst):
    # do stuff

You could even place it in a function to make it look nicer.

def string_minus_exclusions(string, exclusions):
    for phrase in exclusions:
        string = string.replace(phrase, '')
    return string

string = 'will be in every day for each week'
lst = ['for','and','with','be in']
exclusions = ['for every','for each']
replaced = string_minus_exclusions(string, exclusions)
if any(word in replaced for word in lst):
    # do stuff