Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String match with 'in'

In the following code, I would like to search a match for elements in a list in a given string.

lst1 = ['LOP3', 'FOO']
lst2 = ['PLOP3', 'BAR']

x = 'LOP3.LUT'
y = 'PLOP3.LUT'

for i1 in lst1:
    if i1 in x:
        print('yes1')
    if i1 in y:
        print('yes2')

for i2 in lst2:
    if i2 in x:
        print('yes3')
    if i2 in y:
        print('yes4')

When I run the code, I see

yes1
yes2
yes4

That means lst1[0] is found in y which results in yes2. That is wrong in my case. x doesn’t start with PLOP3 although it has LOP3 in its name. So, I would like to see yes1, yes4 only. How can I fix that code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

"That means LOP3 is found in lst1[0] which results in yes2."

No, lst1[0], 'LOP3', is found in y, 'PLOP3.LUT'. Other way around. That causes it to print yes2. So perhaps you want to reverse that expression, a in b to b in a?

Or perhaps you want the startswith method, e.g. if x.startswith(i1):?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading