I’d like to make an if statement to detect if a string could be formed with items from lists, in order. For example, if I want to check if a term had the same meaning as “HelloWorld”, I’d have a “hello” list with ['hello', 'Hello', 'Hi', 'Greetings', 'Hola'], and a “world” list with ['world', 'World', 'Planet', 'Earth']. Then, check if a string is equal to any item from the “hello” list, directly followed by any item from the “world” list. “HelloWorld”, “GreetingsEarth”, and “HiPlanet” would all successfully trip the if statement. How would I do this? I’d like to use Python lists, so regex (a|b) seems impractical.
I’d like to make an if statement to detect if a string could be
Share
If you want to avoid a regular expression, you can use a generator expression that tests each combination (generated via
itertools.product):Note that this is far slower than the regular expression approach, especially when hitting the worst-case scenario (no match):
The generator expression is 10 times slower than the regular expression approach.
(I used a
re.compile()compiled regular expression for the test).