Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first list index containing sub-string?

Tags:

python

list

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.

like image 329
c00kiemonster Avatar asked Jan 31 '10 07:01

c00kiemonster


People also ask

How do you find the index of the first occurrence of a substring in a string?

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.

How do you find the position of a substring in a string in Python?

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.

What does STR find sub return when sub is not in string str?

If "sub" cannot be found then -1 is returned.


1 Answers

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 
like image 63
kennytm Avatar answered Sep 29 '22 23:09

kennytm