In the following code, I would like to search a match for elements in a list in a given string.
JavaScript
x
18
18
1
lst1 = ['LOP3', 'FOO']
2
lst2 = ['PLOP3', 'BAR']
3
4
x = 'LOP3.LUT'
5
y = 'PLOP3.LUT'
6
7
for i1 in lst1:
8
if i1 in x:
9
print('yes1')
10
if i1 in y:
11
print('yes2')
12
13
for i2 in lst2:
14
if i2 in x:
15
print('yes3')
16
if i2 in y:
17
print('yes4')
18
When I run the code, I see
JavaScript
1
4
1
yes1
2
yes2
3
yes4
4
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):
?