Victor Victor - 6 months ago 11
Python Question

Check a string for any items in an array

I have an string (items with comma separated) and I need to check if any of the items in the string (or list after split) are present in a long string.

I know how to do this in a long style like:

people="first,second"
test='hello_first'

for i in people.split(","):
if i in test :
print 'found'


Is there a better way to combine
for
and
if
in one line ?

e.g. using
any
or something?

if any(x in people.split(",") for x in test) :
print 'found'


doesn't seem to print 'found'.

Answer

Use any checking if any word is in test :

if any(word in test for word in people.split(",")):
   # do whatever

Your logic is incorrect as you are checking test is in the split list of words which does not match your first loop.