looping question 4 NEWB

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Thu Jul 6 07:08:24 EDT 2006


manstey schreef:
> Hi,
> 
> I often have code like this:
> 
> data='asdfbasdf'
> find = (('a','f')('s','g'),('x','y'))
> for i in find:
>    if i[0] in data:
>        data = data.replace(i[0],i[1])
> 
> is there a faster way of implementing this? Also, does the if clause
> increase the speed?

I think this is best done with translate() and string.maketrans() (see 
http://docs.python.org/lib/node110.html#l2h-835 and 
http://docs.python.org/lib/string-methods.html#l2h-208). An example:

import string

data = 'asdfbasdf'
translatetable = string.maketrans('asx', 'fgy')
data = data.translate(translatetable)
print data

This results in:

fgdfbfgdf

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list