[Tutor] Looking for Words - Help
Mark Lawrence
breamoreboy at yahoo.co.uk
Fri Oct 11 16:40:33 CEST 2013
On 11/10/2013 15:23, Peter Otten wrote:
> Alan Gauld wrote:
>
>>> Use the stripw() function we saw on individual words to make
>>> finding hits more accurate
>>
>> No idea what that means but since the assignment suggests
>> it we should assume its correct.
>
> My crystal ball says
>
> def stripw(word):
> return word.strip('",.')
>
> or somesuch.
>
>> You have several bad habits in here...
>>
>>> def lines(name, word):
>>> 'print all lines of name in which word occurs'
>>>
>>> infile = open(name, 'r')
>>> lst = infile.readlines()
>>> infile.close()
>>
>> You could do that in one line:
>>
>> lst = open(name).readlines()
>
> Talking about bad habits -- what you are suggesting here is a step in the
> wrong direction.
>
> If at this point in the OP's Python career you bother about how to open and
> close a file at all you should recommend the safe variant
>
> with open(name) as infile:
> lines = infile.readlines()
>
> rather than the version for, err, us lazy old bastards ;)
>
Why bother building a list when the modern idiom is simply
for line in infile: ?
--
Roses are red,
Violets are blue,
Most poems rhyme,
But this one doesn't.
Mark Lawrence
More information about the Tutor
mailing list