1

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Ah yes, I see how that will work, although I think it breaks when you set replaced_string = '', so I have changed it to replaced_string = string.replace(phrase, '')
You're right. I wasn't testing and just defaulted to an empty string. replaced_string = '' should be replaced_string = string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.