Rita Sue and Bob too

Neal Holtz nholtz at docuweb.ca
Fri Aug 20 18:50:26 CEST 2004


"Ben Last" <ben at benlast.com> wrote in message news:<mailman.2010.1092985999.5135.python-list at python.org>> 
> seqToFind = ['Rita','Sue','Bob']
> seqToReplace = ['A','B','C']
> seqToSearch =
> ['Ben','Peter','Guido','Mark','David','Rita','Sue','Bob','Junk','Extra']
> ...
> 
> That last block could also be written as:
> 
> #s ends up with the resulting list
> s = seqToSearch
> s =
> string.join(seqToSearch,joiner).replace(string.join(seqToFind,joiner),string
> .join(seqToReplace,joiner)).split(joiner)
> 
> But that's verging on the obfuscated :)

Very perlish indeed.

But the above fails if the first or last words in seqToFind are
trailing
or leading substrings of other words in seqToSearch.  IE, if> 
seqToSearch =
 ['Ben','Peter','Guido','Mark','David','Rita','Sue','BobbyJoe','Junk','Extra']

So something that fails slightly less often:

def repseq4( names, old, new ):
    s = '\003'; return
((s+s.join(names)+s).replace(s+s.join(old)+s,s+s.join(new)+s,1)).split(s)[1:-1]

It turns out that this is actually faster than the more obvious
methods
(by about 25% (over Jeremy Jones' method) for a names list of 1000
names, replacing the middle 3).
Sure is ugly, though.



More information about the Python-list mailing list