looping question 4 NEWB

Simon Forman rogue_pedro at yahoo.com
Thu Jul 6 11:30:54 EDT 2006


bearophileHUGS at lycos.com wrote:
> manstey:
> > is there a faster way of implementing this? Also, does the if clause
> > increase the speed?
>
> I doubt the if increases the speed. The following is a bit improved
> version:
>
> # Original data:
> data = 'asdfbasdf'
> find = (('a', 'f'), ('s', 'g'), ('x', 'y'))
>
> # The code:
> data2 = data
> for pat,rep in find:
>     data2 = data.replace(pat, rep)
> print data2

Small bug in that code, you'll wind up with data2 only being the result
of replacing the last (pat, rep) in find.  It should be:

data2 = data
for pat, rep in find:
    data2 = data2.replace(pat, rep)

Be careful with multi-char terms in find.  You could wind up replacing
patterns that only occur in data2 as a result of earlier replacements.

I.e. if
find = ('bc', 'ab'), ('aa', 'bb')
data = 'abc'

then
data2 = 'aab' # First iteration,
data2 = 'bbb' # Second iteration replaces 'aa' even though 'aa' isn't
in original data.

Have fun,
~Simon


>
> # If find contains only chars, and the string is long
> # enough, then this is more or less the faster solution:
>
> from string import maketrans
> table = map(chr, xrange(256))
> for c1,c2 in find:
>     table[ord(c1)] = c2
> table_str = "".join(table)
> print data.translate(table_str)
> 
> Bye,
> bearophile




More information about the Python-list mailing list