Verify if an element of a list is in a string

Verify if an element of a list is a a string

I have a list of key words:

check_list  = ['aaa','bbb','ccc']

And a group of strings:

test_string_1 = 'hellor world ccc'
test_string_2 = 'hellor world 2'

And I want to verify if any of the elements of the list is in the string

for key in check_list:
    if key in test_string_1:
        print 'True'

But instead of printing a value return True or False

So I can do this:

if some_conditions or if_key_value_in_test_string:
    do something

Upvotes: 2

Views: 82

Answers (2)

tom10
tom10

Reputation: 69172

If I understand right what you want, you can do:

def test(check_list, test_string)
    for key in check_list:
        if key in test_string:
            return True
    return False

or in a single line you could do:

any([key in test_string for key in check_list])

or use a generator expression, which might be advantageous for long lists since it will short circuit (that is, stop at the first True without building the full list first):

any(key in test_string for key in check_list)

Upvotes: 3

user2754799
user2754799

Reputation: 104

use built-in functions

>>> check_list  = ['aaa','bbb','ccc']
>>> test_string_1 = 'hellor world ccc'
>>> test_string_2 = 'hellor world 2'
>>> any([(element in test_string_1) for element in check_list])
True
>>> any([(element in test_string_2) for element in check_list])
False
>>> 

Upvotes: 2

Related Questions