Reputation: 23
I'm looking for a string within a list of strings and the string to be found is a subset of one of the strings in the "search" list I need a way to get in which item of the list was the string found example:
mylist = ['hola pepe', 'hola manola', 'hola julian', 'holasofi']
searchitem1 = 'pepe'
searchitem2 = 'sofi'
I tried:
mylist.index('pepe')
but didn't work (as its not the exact string I guess?) I also tried:
if any(ext in 'pepe' for ext in mylist): mylist.index(ext)
but didn't work either.... What i'm looking at Is like stopping when the string is found and getting from the code in which item the find occurred....
thanks!
Upvotes: 2
Views: 87
Reputation: 4964
If you are new to Python, maybe you are better by now with the classical approach in Chris answer. But if you feel curious about generators see the following example using a generator expression (essentially the same as Chris answer but more compact):
>>> mylist = ['hola pepe', 'hola manola', 'hola julian', 'holasofi', 'oi pepe']
>>> gen = ((index,elem) for index, elem in enumerate(mylist) if 'pepe' in elem)
>>> next(gen)
(0, 'hola pepe')
>>> next(gen)
(4, 'oi pepe')
>>> next(gen)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
The indexes can be extracted as usual like in
>>> next(gen)[0]
A generator object is always created even if there are no elements that match the if clause in the generator expression.
To handle the exception when next()
does not yield more values use a try
block to capture the StopIteration
:
search = 'pepe'
...
try:
next_result = next(gen)
except StopIteration:
print('No more matches for {}'.format(search))
Upvotes: 1
Reputation: 11992
You can write a function that will return when it finds the first index that contains the string your interested in. Alternativly if you want all indexs that contain the string you can use yield to create a generator that will produce all the indexs that contain the string.
def get_first_index_contains(mylist, mystring):
for index, element in enumerate(mylist):
if mystring in element:
return index
def get_all_index_contains(mylist, mystring):
for index, element in enumerate(mylist):
if mystring in element:
yield index
mylist = ['hola pepe', 'hola manola', 'hola julian', 'holasofi']
searchitem1 = 'pepe'
searchitem2 = 'sofi'
print(get_first_index_contains(mylist, searchitem1))
print(get_first_index_contains(mylist, searchitem2))
print(list(get_all_index_contains(mylist, 'hola')))
OUTPUT
0
3
[0, 1, 2, 3]
Upvotes: 1