search for pattern in StringList

Remco Gerlich scarblac at pino.selwerd.nl
Mon Dec 18 12:25:18 EST 2000


Daniel <Daniel.Kinnaer at AdValvas.be> wrote in comp.lang.python:
> As a Python newbie, I was trying a very simple exercise, but got
> stuck. Is there someone who can help me complete this code, please?
> 
> 
> 
> MyList = ['an','been','call','door']
> 
> print "Scanning a StringList"
> 
> for i in range(0, len(MyList)):
>     print i, MyList[i]
> 
> #try to show every item in MyList which contains an 'a'
> #that is 'an' and 'call'.   In Pascal :
> #for i:=0 to MyList.Items.Count -1 do
> #    if pos('a',MyList.Items[i])>0 then writeln(MyList.Items[i]) 
> #in Python : ???

A string is a list of characters. To see if the list contains 'a', you
can use the 'in' operator:

>>> 'a' in 'bla'
1

Then the for statement becomes:

for s in MyList:
   if 'a' in s: 
      print s

If you're looking for strings longer than a single character, you can't
use 'in', you have to use the find() method:

for s in MyList:
   if s.find('ab') != -1:
      print s
 
This is a very common thing to do, select some items from a list based
on some criterium. filter() is a built-in function that does this:

print filter(MyList, lambda x: 'a' in x)

It "filters" the list according to the simple function given by the lambda,
that tests if 'a' in x.

Since Python 2.0, there is yet another way to write this:

print [s for s in Mylist if 'a' in s]

This is derived from set notation in math; it is 'the list of s, where
s comes from MyList and only those where "a" in s'.

For this simple example, these other options may be overkill, but
it's not a bad thing to know about them ;).


-- 
Remco Gerlich



More information about the Python-list mailing list