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.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to