Reputation: 21
I am new to python and I have simple problem with code below the code supposed to give the result 'x100' while it is 'x10' and 'x100'.How to get the result as expected.
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
if text.find(i)!=-1:
print "found "+i
>>>
found x10
found x100
>>>
Upvotes: 0
Views: 101
Reputation: 43437
You can use this simple list-comprehension to find all instances. Bonus: it only calculates the split once.
def f(s, lst):
return [item for item in lst if item in s.split()]
Test it:
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> f(text, test_list)
['x100']
Upvotes: 0
Reputation: 52071
A simpler way would be
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
if i in text.split():
print "found "+i
To detect
test_list=['x10','x50','x100']
test_list= sorted(test_list,key = lambda x: len(x), reverse = True)
text='this text has x100n only'
import re
a = re.search("|".join(test_list),text)
if a:
print "Found",a.group()
Upvotes: 1
Reputation: 16556
You could use .split()
to find if it's in the list of word:
>>> test_list=['x10','x50','x100']
>>> text='this text has x100 only'
>>> for i in test_list:
... if i in text.split():
... print "found",i
...
found x100
Upvotes: 1