substitution

Nobody nobody at nowhere.com
Mon Jan 18 10:09:31 EST 2010


On Mon, 18 Jan 2010 11:21:54 +0100, superpollo wrote:

>> what is the most pythonic way to substitute substrings?

> say the subs are:
> 
> quuux --> foo
> foo --> bar
> baz --> quux
> 
> then i cannot apply the subs in sequence (say, .replace() in a loop), 
> otherwise:
> 
> fooxxxbazyyyquuux --> fooxxxbazyyyfoo --> barxxxbazyyybar --> 
> barxxxquuxyyybar
> 
> not as intended...

Are there any characters which are guaranteed never to occur in the
string? If so:

s = s.replace('quuux', '@1').replace('foo', '@2').replace('baz', '@3')
s = s.replace('@1', 'foo').replace('@2', 'bar').replace('@3', 'quux')

E.g.:

def replace(subs, s):
  for i, (src, dst) in enumerate(subs):
    s = s.replace(src, '@%06d' % i)
  for i, (src, dst) in enumerate(subs):
    s = s.replace('@%06d' % i, dst)
  return s

Not the most efficient solution (and problematic if there aren't any
"unused" characters), but somewhat shorter than the other solutions.




More information about the Python-list mailing list