Home > OS >  Find all instances of a sub-string in a list of strings and return the index of the string where the
Find all instances of a sub-string in a list of strings and return the index of the string where the

Time:11-05

How would I find all instances of a sub-string in a list of strings and return the index of the string where the sub-string is found in Python?

For example:

sub_string = "tree"
my_list = ["banana", "tree", "trees", "street"]

The desired output would be: [1,2,3] as tree is found within the strings at the indices of 1, 2, 3.

I have this in the form of a function but it only returns the first instance of the sub-strings index and doesn't recognize the sub-string in a string (tree in street for example).

def inside_search(a_list, search_term):
    if search_term in a_list:
        index = a_list.index(search_term, 0, -1)
        return [index]
    else:
        return []

cats_and_dogs_list = ["cat", "cats", "dog", "dogs", "catsup"]
print(inside_search(cats_and_dogs_list, "cat"))

My function returns [0] but I want it to return [0,1,4]

I have tried and solved this several ways using several methods but I can't seem to return anything but [0].

CodePudding user response:

Use list comprehension with enumerate:

>>> [i for i, w in enumerate(my_list) if sub_string in w]
[1, 2, 3]

If you want to use a function:

def inside_search(a_list, search_term):
    result = list()
    for i, word in enumerate(a_list):
        if search_term in word:
            result.append(i)
    return result

>>> inside_search(cats_and_dogs_list, "cat")
[0, 1, 4]

CodePudding user response:

This is what you're looking for:

print([my_list.index(item) for item in my_list if sub_string in item])

Hope this helped :) Cheers!

  • Related