Connor J
Connor J

Reputation: 570

Python - Check if part of a string exists in a list and give the index of its match

I'm trying to get a piece of code to return the index of where the match was found within the list, so that another item can be compared to this index. (essentially allowing two separate strings to be compared to the same item on a list). I'm able to get the match if it matches exactly, but can't get it to work with a partial string. Here is some pseudo code to show what I have:

mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']
str1 = 'does mn have anything to do with it?'
str2 = 'I think mn is there'

b = [i for i, s in enumerate(mylist) if str1 in s]
print(b)

So my question is how can I get the index of 'mno' to return so that I can compare str2 against it after the first check. If there's a better way around this problem id love to hear it

Upvotes: 1

Views: 4703

Answers (5)

Aniket Parulekar
Aniket Parulekar

Reputation: 124

This may help as in str2 you are searching specific keyword which is "mn" so we split str1 into simple list of words and then traverse the list to find occurrences of partial mn in items.

mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']

str1 = 'does mn have anything to do with it?'
str2 = 'I think mn is there'

for i in str1.split(" "):
    for j in mylist:
    if i in j:
        print("match found and its for " + i + " which is partially exist in " + j)

Upvotes: 0

JimmyA
JimmyA

Reputation: 686

Maybe it would be best to put this into a function?

str = 'does mno have anything to do with it?'
str2 = 'I think mn is there'
mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']

def are_you_here(str, list):
    return [list.index(x) for x in list if x in str]

are_you_here(str, mylist)
are_you_here(str2, mylist)

Output:

[4]
[]

Upvotes: 0

Vishal Khichadiya
Vishal Khichadiya

Reputation: 430

Maybe this one can help!!

mylist = ['abc', 'def', 'ghi', 'jkl', 'mno']
str1 = 'does mn have anything to do with it?'
str2 = 'I think mn is there'

b = [i  for i, s in enumerate(mylist) for st in str2.split(' ') if st in s]
print(b)

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191733

From the question, str1 in s will never be true since no element of mylist contains the entire str1 string.

Assuming word boundaries are important, you can split the string, then find indexes of the string containing that token

b = [] 
for s1 in str1.split():
    for i, s2 in enumerate(mylist):
        if s1 in s2:
            b.append(i)

Upvotes: 2

Ashish Acharya
Ashish Acharya

Reputation: 3399

How about like this:

b = []
for i in str1.split():
    for idx, j in enumerate(mylist):
        if i in j:
            b.append(idx)

...or if you're looking for a list comprehension:

b = [idx for i in str1.split() for idx, j in enumerate(mylist) if i in j]

Output:

[4]

Upvotes: 2

Related Questions