search for pattern in StringList

Alex Martelli aleaxit at yahoo.com
Mon Dec 18 10:33:23 EST 2000


"Daniel" <Daniel.Kinnaer at AdValvas.be> wrote in message
news:3a3e1935.5461298 at news.skynet.be...
> 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?
>
> Thanks.
> Daniel
>
>
> MyList = ['an','been','call','door']
>
> print "Scanning a StringList"
>
> for i in range(0, len(MyList)):
>     print i, MyList[i]

Note that
    for i in range(len(MyList)):
is equivalent (0 is the default starting value for range).

> #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 : ???

In Python, it can be a little bit more "conceptually concise",
thanks to the for-in statement (one can iterate on the
items of a sequence directly, rather than iterating on
the indices and using indexing in the body, when the
index itself isn't needed):

for item in MyList:
    if item.find('a')>0:
        print item


It's not *necessary* to break the 'if', since its body
is a single, simple statement -- you *could* also write:

for item in MyList:
    if item.find('a')>=0: print item

but the normal Python convention is to end the line at
any ':' (which concludes such statements as for, while,
if, def, ... -- 'compound statements', basically), and
then (this is not just convention, but a key Python
lexical rule) you have to indent the statement's body
uniformly.


Alex






More information about the Python-list mailing list