substitution

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jan 18 06:10:39 EST 2010


On Mon, 18 Jan 2010 11:15:37 +0100, superpollo wrote:

> hi.
> 
> what is the most pythonic way to substitute substrings?
> 
> eg: i want to apply:
> 
> foo --> bar
> baz --> quux
> quuux --> foo
> 
> so that:
> 
> fooxxxbazyyyquuux --> barxxxquuxyyyfoo

For simple cases, just use replace:


>>> s = 'fooxxxbazyyyquuux'
>>> s = s.replace('foo', 'bar')
>>> s = s.replace('baz', 'quux')
>>> s = s.replace('quuux', 'foo')
>>> s == 'barxxxquuxyyyfoo'
True


In complicated cases, such as if there are conflicts or overlaps between 
strings, you may need to use a regular expression, or even parse the 
string yourself.

The problem is that "substitute multiple strings" is not well defined, 
because in general it depends on the order you perform them. You can 
define a function to do the replacements in one order, but for another 
use you might need a different order.

E.g.: replacing "a" -> "X" and "aa" -> "Y", if you have the string "aaa" 
what result do you expect? You could get "XXX", "XY" or "YX". None of 
these are wrong, it depends on which you prefer.


-- 
Steven



More information about the Python-list mailing list