[Tutor] ".=" in Python ?

Jeff Shannon jeff@ccvcorp.com
Mon May 5 17:10:12 2003


Tadahiko 'kiko' Uehara wrote:

>I have a text file which contains something like:
>------------------------------
>irc.foo1.com
>irc.foo2.com
>irc.foo3.com
>------------------------------
>
>and I'm trying to generate list as following:
>------------------------------
>servername = irc.foo1.com
>servername = irc.foo2.com
>servername = irc.foo2.com
>------------------------------
>

What are you planning on doing with this list??  There's a few ways that 
you can approach this, that look a fair bit different from what you're 
doing, but the best approach depends on what exactly the desired end 
result is.  Your script, as it stands, will create a single multiline 
string -- is that what you actually want, or would a list of lines be 
better?  In any case, I'd write it something like this:

f = file('/home/kiko/docs/serverList')
lines = f.readlines()    # this reads the entire file, creating a list 
of lines
f.close()
modlines = []    # an empty list
for line in lines:
    modline = "servername = %s" % line
    modlines.append(modline)
modtext = ''.join(modlines)    # optional

First, I read the entire file into a list of lines, because lists are 
convenient to work with in Python.  Once I have that, I create a new, 
empty list.  I then iterate over my list of lines, for each one creating 
a modified line using string formatting, and adding that modified line 
to my new list.  Once I've done that for all lines, I then join the list 
of modified lines into a single string.  (Note that readlines(), as well 
as readline(), will leave the '\n' at the end of every line of the file. 
 I leave that alone so that my final result still contains the newlines 
in the appropriate places.  If I wanted to use these lines as a list, 
instead of a single string, I'd probably want to strip off the newlines, 
which could be done by calling line.strip() during the string-formatting 
-- i.e., 'modline = "servername = %s" % line.strip()'.  I'd be left with 
a set of lines that I could then easily iterate over again.)

This could be condensed quite a bit, especially by using a list 
comprehension:

f = file('/home/kiko/docs/serverList')
modlines = ["servername = %s" % line.strip() for line in f.readlines()]
f.close()

Hopefully this makes sense, and the cold medicine I'm taking hasn't 
addled my brains too much. :)

Jeff Shannon
Technician/Programmer
Credit International