Need help on reading line from file into list

Duncan Booth duncan.booth at invalid.invalid
Wed Apr 4 04:05:44 EDT 2007


"bahoo" <b83503104 at yahoo.com> wrote:

> I don't see where the "str" came from, so perhaps the output of
> "open('source.txt').readlines()" is defaulted to "str?

Apart from Grant's explanation that str is the type of a string, what you 
perhaps haven't yet grasped is that if you have a type and an instance of 
that type there is an equivalence between calling a method on the instance, 
or calling the method directly on the type and passing the instance as the 
first parameter.

i.e. Given a type T and an instance I (so that type(I)==T) the following 
two are equivalent:

    I.method(args)
    T.method(I, args)

what that means in this particular case is that if you have a string 
'line' and want to strip leading and trailing whitespace you can call 
either:

   line.strip()
or:
   str.strip(line)

So str.strip is just another way to refer to the strip method of a str (but 
you do have to know that the line is a str rather than another type or it 
won't work).



More information about the Python-list mailing list