Pythonic way of searching for a substring in a list
list, python, string, substring
Solution
You can also use a list comprehension :
matches = [s for s in mytext if 'foobar' in s]
(and if you were really looking for strings starting with 'foobar' as THC4k noticed, consider the following :
matches = [s for s in mytext if s.startswith('foobar')]
Problem
I have a list of strings - something like ``` mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] ``` I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this ``` for i in mytext: index = i.find("foobar") if(index!=-1): print i ``` Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this? Cheers, Mike