newbie question: for loop within for loop confusion

takayuki lawtonpaul at gmail.com
Mon Jun 16 20:55:10 EDT 2008


On Jun 17, 6:34 am, Thomas Hill <tomlikestor... at gmail.com> wrote:
> On Jun 15, 6:23 pm, takayuki <lawtonp... at gmail.com> wrote:
>
> > def hasnolet(avoid):
> >         fin = open('animals.txt')
> >         for line in fin:
> >                 word = line.strip()
> >                 for letter in avoid:
> >                         if letter in word:
> >                                 break
> >                         else:
> >                                 print word
>
> You're using the split command correctly, but you're not filtering
> correctly. Consider this:
>
> ---begin---
> fin = open('animals.txt')
> "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) ==
> len(line)])
> ----end----
>
> Let's go slow.
>
> "\n".join([...])
>
> 1. Take everything that is in the following list, and print each one
> with a carriage return appended to it.
>
> "\n".join(["%s" % line for line in fin ...])
>
> 2. For each line in fin, create a string that only consists of what
> currently in the line variable, using string substitution.
>
> "\n".join(["%s" % line for line in fin if len(line.strip('abcd')) ==
> len(line)])
>
> 3. Only do #2 if the length of the line after stripping out the
> unnecessary characters is the same length as the line originally. This
> way we filter out the lines we don't want. If we wanted the lines that
> have been filtered, we can change "==" to "!=" or "<=".
>
> Now, I read "Dive Into Python" first, which through these early on in
> the book. If your eyes cross looking at this, write it down and read
> it again after you get a little farther into the book you're reading

Thomas,

thanks for the reply.

I'm early on in my python adventure so I'm not there yet on the strip
command nuances.    I'm reading "How to think like a python
programmer" first.  It's great.

Then "Learning python".  I've read parts of Dive into Python and will
work through it fully when I'm a little farther along.

takayuki



More information about the Python-list mailing list