substitution

Mel mwilson at the-wire.com
Mon Jan 18 09:44:50 EST 2010


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

This is simple -- maybe a bit brutal -- and if the strings get long it will 
be slow:


def replaced (input, replacements):
    output = []
    while input:
        for target in replacements:
            if input.startswith (target):
                output.append (replacements [target])
                input = input [len (target):]
                break
        else:
            output.append (input[0])
            input = input [1:]
    return ''.join (output)
        
original = 'fooxxxbazyyyquux'
replacements = {'quux':'foo', 'foo':'bar', 'baz':'quux'}
print original, '-->', replaced (original, replacements)




	Mel.




More information about the Python-list mailing list