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?
Advertisement
Answer
“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):
?