'searching for a string that contains 2 or more known sub strings

That's my approach

title = ('one two three four')


if 'one' and 'three' in title:
    print('Found')
else:
    print('not found')

but it always returns found

I want it to return found only when both of the substrings exist together, not one of them



Solution 1:[1]

That’s because it checks conditions on both side of and. Instead you should be doing;

if "one" in title and "three" in title:
    print("Found")
else:
    print("Not Found")

Solution 2:[2]

Alternately to the answer by @FishballNooodles, we can use all and a generator expression to solve this.

if all(word in title for word in ('one', 'three')):
    print('found')
else:
    print('Not found')

The chief benefit of this approach is how easy it is to extend the list of words that have to be included.

Another slightly more esoteric approach would be to leverage the fact that str.index raises a ValueError exception if the substring cannot be found. In this case we have to use any because str.index might return 0 which will be interpreted as false in a boolean context and will let all exit early.

try:
    any(map(title.index, ['one', 'three']))
    print('Found')
except ValueError:
    print('Not found')

If mapping title.index to each of the substrings completes, that means all of them were found, and we can print 'Found'. Otherwise the except ValueError clause will print 'Not found'.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MoRe
Solution 2