Luis Ramon Ramirez Rodriguez Luis Ramon Ramirez Rodriguez - 4 months ago 11
Python Question

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

Answer

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)