It's ...

Scott David Daniels Scott.Daniels at Acm.Org
Wed Jun 24 23:10:54 CEST 2009


Angus Rodgers wrote:
> ... my first ... question is how best to find out what's changed from version 2.1 
 > to version 2.5. (I've recently installed 2.5.4)
Consecutively read:
     http://docs.python.org/whatsnew/2.2.html
     http://docs.python.org/whatsnew/2.3.html
     http://docs.python.org/whatsnew/2.4.html
     http://docs.python.org/whatsnew/2.5.html

> stop = 3   # Tab stops every 3 characters
Typically program constants should be full caps.  See PEP 8

> from types import StringType   # Is this awkwardness necessary?
Nope

> detab = lambda s : StringType.expandtabs(s, stop)  # Or use def

Really use def unless you have a solid reason not to.  At the moment,
I'd suggest you simply presume you have no such reason.
Also, expandtabs is an instance method, so the roundabout is not needed.

     def detab(s):
         return s.expandtabs(stop)

> f = open('h071.txt')   # Do some stuff to f, perhaps, and then:
> f.seek(0)
> print ''.join(map(detab, f.xreadlines()))
Too much, even though that is how you thought the problem out.
First, text files are now iterable (producing a line at a time
much like xreadlines).  Second the map above creates a list of
all detabbed lines, then (while that list still exists), it also
creates a string constant which is the "new" contents of the file.

I'd simply use:
     for line in f:
         print detab(line.rstrip())
or even:
     for line in f:
         print line.rstrip().expandtabs(stop)

 > ...
> g.writelines(map(detab, f.xreadlines()))
> 
> In practice, does this avoid creating the whole string in memory
> at one time, as is done by using ''.join()?
Nope.  But you could use a generator expression if you wanted:
      g.writelines(detab(line) for line in f)

> OK, I'm just getting my feet wet, and I'll try not to ask too many
> silly questions!
> 
> First impressions are: (1) Python seems both elegant and practical;
> and (2) Beazley seems a pleasantly unfussy introduction for someone 
> with at least a little programming experience in other languages.
Both 1 and 2 are true in spades.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list