looping question 4 NEWB

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


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

 > But what about substitutions like:
 > 'ab' > 'cd', 'ced' > 'de', etc
 >
 > what is the fastest way then?

Ah, in that case I don't think you can do much better than you already 
did. But I think the if clause doesn't increase the speed; it might even 
decrease it. If you want to know for sure, use timeit to see what's fastest.

-- 
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