looping question 4 NEWB
manstey
manstey at csu.edu.au
Sun Jul 9 17:15:16 EDT 2006
Thanks Marc, that was very helpful.
Marc 'BlackJack' Rintsch wrote:
> In <1152182594.168085.10660 at m73g2000cwd.googlegroups.com>, manstey wrote:
>
> > 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?
>
> It decreases it. You search through `data` in the ``if`` clause. If it's
> `False` then you have searched the whole data and skip the replace. If
> it's `True` you searched into data until there's a match and the the
> `replace()` starts again from the start and searches/replaces through the
> whole data.
>
> You can get rid of the indexes and make the code a bit clearer by the way:
>
> for old, new in find:
> data = data.replace(old, new)
>
> Ciao,
> Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list