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!
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))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments