looping question 4 NEWB

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Jul 6 07:19:14 EDT 2006


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

# 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