Skip to content Skip to sidebar Skip to footer

Matching String Contains X And Followed By Y

I want to evaluate to true if a string contains the word ‘except’ AND is followed by ‘xyz’. For example blah except xyz => true except xyz => true blah except abc =&g

Solution 1:

How about with string operations?

if'except'in my_string.lower() and my_string.lower().find('xyz') > my_string.lower().find('except'):
    return True

You could also use EAFP and avoid looking for 'except' twice:

try:
    if my_string.lower().index('xyz') > my_string.lower().index('except'):
        returnTrueelse:
        returnFalseexcept ValueError:
    returnFalse

It's simpler if you only need truthy/falsey values rather than actual booleans:

try:
    if my_string.lower().index('xyz') > my_string.lower().index('except'):
        returnTrueexcept ValueError:
    return

Solution 2:

This is one of those cases where regex does make sense:

if re.search('except.*xyz', string):
    ...

Simple, fast and elegant.

Solution 3:

I think this is most readable:

'except' in my_string and'xyz' in my_string.split('except', 1)[1]

Post a Comment for "Matching String Contains X And Followed By Y"