Brian Powell
Brian Powell

Reputation: 3411

python - finding multiple strings in multiple strings

I can use this to determine whether or not any of a set of multiple strings exist in another string,

bar = 'this is a test string'
if any(s in bar for s in ('this', 'test', 'bob')):
    print("found")

but I'm not sure how to check if any of a set of multiple strings occur in any of many strings. It seems like this would work. Syntactically it does not fail, but it doesn't print me out anything either:

a = 'test string'
b = 'I am a cat'
c = 'Washington'
if any(s in (a,b,c) for s in ('this', 'test', 'cat')):
    print("found")

Upvotes: 1

Views: 4144

Answers (3)

Jon Clements
Jon Clements

Reputation: 142106

At this point it's probably worth compiling a regular expression of the substrings you're looking for and then just apply a single check using that... This means that you're only scanning each string once - not potentially three times (or however many substrings you're looking for) and keeps the any check at a single level of comprehension.

import re

has_substring = re.compile('this|test|cat').search
if any(has_substring(text) for text in (a,b,c)):
    # do something

Note you can modify the expression to only search for whole words, eg:

has_word = re.compile(r'\b(this|test|cat)\b').search

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

a = 'test string'
b = 'I am a cat'
c = 'Washington'

l = [a, b, c]

tests = ('this', 'test', 'cat')

if any(any(i in b for b in l) for i in tests):
    print("found")

Upvotes: 1

thaavik
thaavik

Reputation: 3317

Need to iterate through the tuple of test strings:

a = 'test string'
b = 'I am a cat'
c = 'Washington'
if any(s in test for test in (a,b,c) for s in ('this', 'test', 'cat')):
    print("found")

Upvotes: 2

Related Questions