views:

280

answers:

5

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

+6  A: 
for s in lst:
    if 'foobar' in s:
         print(s)
SilentGhost
+5  A: 
results = [ s for s in lst if 'foobar' in s]
print(results)
Clay
+13  A: 

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')]
Altherac
Now I'm wondering if doing this as a generator is better: matches = (s for s in mytext if s.startswith('foobar')) Anyone knows?
Koen Bok
@Koen It's better to use a generator if (a) the result list would be large (although it would only consist of references to the original strings), and (b) you do not need to have the result in one piece, e.g. to do a len(matches) or a matches[-1], but rather want to iterate through it.
ThomasH
+4  A: 

in case you really looking for strings that start with foobar ( not with foobar in them):

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

or

found = [ s for s in mylist if s.startswith('foobar') ]
THC4k
+8  A: 

If you really want the FIRST occurrence of a string that STARTS WITH foobar (which is what your words say, though very different from your code, all answers provided, your mention of grep -- how contradictory can you get?-), try:

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

this gives an empty string as the found result if no item of mylist meets the condition. You could also use itertools, etc, in lieu of the simple genexp, but the key trick is this way of using the next builtin with a default (Python 2.6 and better only).

Alex Martelli
+1 I was just cracking my head over a (s for s in...)[0] expression, to get just the first item, and wondered what to do if there is no first item...
ThomasH
@ThomasH, yeah, in 2.5 you had to do a `try: / x=blah.next() / except StopIteration`, 2.6's builtin `next` is much handier!
Alex Martelli