Newbie Question

jmdeschamps at jmdeschamps at
Tue Jun 20 04:31:38 CEST 2006

placid wrote:
> BartlebyScrivener wrote:
> > Saint Malo wrote:
> > > If the program searches for blue, i just want it to print blue
> >
> > Huh? Tell it to print whatever you want.
> >
> > for line in file:
> >     if 'blue' in line:
> >         print 'blue'
> >
> > for line in file:
> >     if 'brown' in line:
> >         print 'brown'
> >
> > for line in file:
> >     if 'red' in line:
> >         print 'weasels rip my flesh'
A little rewrite of the precedent code to make it just a bit closer to
a program (since the OP is a so-called newbie)

myWords=['blue','red','brown'] # you might use a list
for line in myFile:
    for word in myWords:
        if word in line:
            if word != "red":
                print 'weasels rip my flesh'
                print "i found",word

> wow Dude, this is not efficient at all! You only need to read the file
> once not as many times as there are words in your looking for in the
> lines of the file
FWIW, I'm pretty sure the example of BartleByScrivener didn't entail a
new read each time but that it was written for readabilityt purposes
only of the "print what you want" idea... ;-)


More information about the Python-list mailing list