1

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")

3 Answers 3

2

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

Comments

2

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

1 Comment

I appreciate you taking time to answer a question I already accepted an answer on. This is a great idea, and in my case of checking 50 strings against 5 strings, it should actually make things faster and more efficient, so thanks!
1

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")

2 Comments

This is actually really clean, and my real dataset is much larger - this might make things a lot easier to read in the end. Thank you!
@BrianPowell glad I could help!

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.