Skip to content
Advertisement

compare list elment to a string

I have the following list

l=['web','python']

and the following string

st='python, C, something, find' 

I want to check if any element in the list is in the string

I tried using

any(x in l for x in st) 

however it gives false

seems python can’t recognize the element in the string, is there a way to check elements from list to a string if there is a match. i did it successfully using a for a loop and splitting the string to a list however that is not efficient with the real data as it contain a long lists and strings. need something efficient. thanks

Advertisement

Answer

You can use this method

word_list = ['web','python']
string = 'python, C, something, find'   

exist = filter(lambda x : x in string , word_list)
print(list(exist))

output:

['python']
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement