WalkingRandomly
WalkingRandomly

Reputation: 4557

Pythonic way of searching for a substring in a 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 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

Upvotes: 4

Views: 930

Answers (5)

user136698
user136698

Reputation:

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')]

Upvotes: 16

Alex Martelli
Alex Martelli

Reputation: 881477

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).

Upvotes: 9

Clay
Clay

Reputation: 1157

results = [ s for s in lst if 'foobar' in s]
print(results)

Upvotes: 4

Jochen Ritzel
Jochen Ritzel

Reputation: 107588

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') ]

Upvotes: 3

SilentGhost
SilentGhost

Reputation: 319511

for s in lst:
    if 'foobar' in s:
         print(s)

Upvotes: 5

Related Questions