[Tutor] Looking for Words - Help

Alan Gauld alan.gauld at btinternet.com
Sat Oct 12 18:55:34 CEST 2013


On 12/10/13 06:18, Jackie Canales wrote:

>      for line in lst.splitlines():
>          if word in line:
>             words = line

Notice that you are overwriting words each time you get a match.
So the final value of words at the end of the for loop will just be the 
last line found. All earlier lines will have been lost.

However, as Dave points out, this is the wrong approach to the 
assignment. You should be getting all the words not just lines that 
contain the word because the context(=/- 5 words) might span lines into 
lines that do not of themselves contain your word. So this approach 
throws away words which you may need.

>      for index, word in enumerate(words):
>          print(words)

The obvious error of using words instead of word has already been 
pointed out. But since we've seen a few errors in your use of for loops 
can I just check you are clear on how Python  for loops work?
If you have used other languages they are like a foreach loop.
They do not use indexing they return each item in a sequence
until the sequence ends. This is much easier than the for loops in 
languages like C, Pascal, Java, Basic etc. enumerate() gives you access 
to indexes on the relatively few occasions you need that extra information.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list