0

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
>>> 
2

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

what about this text 'this text has x100n only'?
@user3522379 That does not work. Do you want that also?
1

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

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.