Multiple string.replace in one run

Alexander Schmolck a.schmolck at gmx.net
Sat Jun 21 22:11:52 CEST 2003


Thomas Güttler <guettler at thomas-guettler.de> writes:

> Hi!
> 
> I want to replace strings in a file:
>  $VAR$ should be replaced with "foo".
> 
> I could do this with string.replace, but
> if I want to replace several variables, I need to
> do the replace several times. Since the file could
> be very long I am searching for a better solution.
> 
> How can I replace several variables at once?

I wrote this function for the purpose. I don't understand why the string class
hasn't such functionality built-in.

def replaceStrs(s, *args):
    r"""Replace all ``(frm, to)`` tuples in `args` in string `s`.

    >>> replaceStrs("nothing is better than warm beer",
    ...             ('nothing','warm beer'), ('warm beer','nothing'))
    'warm beer is better than nothing'

    """
    if args == (): return s
    mapping = dict([(frm, to) for frm, to in args])
    return re.sub("|".join(map(re.escape, mapping.keys())),
                  lambda match:mapping[match.group(0)], s)

'as





More information about the Python-list mailing list