For lists, the method list.index(x)
returns the index in the list of the first item whose value is x
. But if I want to look inside the list items, and not just at the whole items, how do I make the most Pythoninc method for this?
For example, with
l = ['the cat ate the mouse', 'the tiger ate the chicken', 'the horse ate the straw']
this function would return 1
provided with the argument tiger
.
We can use the find() function in Python to find the first occurrence of a substring inside a string. The find() function takes the substring as an input parameter and returns the first starting index of the substring inside the main string. This function returns -1 if the substring isn't present in the main string.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found then it returns -1. Parameters: sub: It is the substring that needs to be searched in the given string.
If "sub" cannot be found then -1 is returned.
A non-slicky method:
def index_containing_substring(the_list, substring): for i, s in enumerate(the_list): if substring in s: return i return -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With