[Tutor] Regular expression re.search() object . Please help

Jeff Shannon jeff at ccvcorp.com
Thu Jan 13 22:29:38 CET 2005


Liam Clarke wrote:

> openFile=file("probe_pairs.txt","r")
> probe_pairs=openFile.readlines()
> 
> openFile.close()
> 
> indexesToRemove=[]
> 
> for lineIndex in range(len(probe_pairs)):
> 
>        if probe_pairs[lineIndex].startswith("Name="):
>                      probe_pairs[lineIndex]=''

If the intent is simply to remove all lines that begin with "Name=", 
and setting those lines to an empty string is just shorthand for that, 
it'd make more sense to do this with a filtering list comprehension:

     openfile = open("probe_pairs.txt","r")
     probe_pairs = openfile.readlines()
     openfile.close()

     probe_pairs = [line for line in probe_pairs \
                           if not line.startswith('Name=')]


(The '\' line continuation isn't strictly necessary, because the open 
list-comp will do the same thing, but I'm including it for 
readability's sake.)

If one wants to avoid list comprehensions, you could instead do:

     openfile = open("probe_pairs.txt","r")
     probe_pairs = []

     for line in openfile.readlines():
         if not line.startswith('Name='):
             probe_pairs.append(line)

     openfile.close()

Either way, lines that start with 'Name=' get thrown away, and all 
other lines get kept.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list