looping question 4 NEWB

manstey manstey at csu.edu.au
Thu Jul 6 07:16:45 EDT 2006


But what about substitutions like:
'ab' > 'cd', 'ced' > 'de', etc

what is the fastest way then?


Roel Schroeven wrote:
> 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