Pythonic substring search in list

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 appearance of anything that starts with foobar. If I were grepping, I would look for foobar *. My current solution looks like this:

for i in mytext:
    index = i.find("foobar")
    if(index!=-1):
        print i

Which works fine, but I wonder if there is a “better” way (like pythonic)?

Cheers, Mike

+3
source share
5 answers

You can also use list comprehension:

matches = [s for s in mytext if 'foobar' in s]

(and if you were really looking for lines starting with "foobar" as THC4k noted, consider the following:

matches = [s for s in mytext if s.startswith('foobar')]
+15
source

FIRST , foobar ( , , , , grep - ?), :

found = next((s for s in mylist if s.startswith('foobar')), '')

found, mylist . itertools .. xp, next ( Python 2.6 ).

+9
for s in lst:
    if 'foobar' in s:
         print(s)
+6
results = [ s for s in lst if 'foobar' in s]
print(results)
+5

, foobar ( foobar ):

for s in mylist:
  if s.startswith( 'foobar' ):
     print s

found = [ s for s in mylist if s.startswith('foobar') ]
+4

Source: https://habr.com/ru/post/1714877/


All Articles