[Python-ideas] in str.replace(old, new), allow 'old' to accept a tuple

Sven Marnach sven at marnach.net
Thu Apr 12 02:41:53 CEST 2012

Tshepang Lekhonkhobe schrieb am Wed, 11. Apr 2012, um 22:35:54 +0200:
> before
> >>> 'foo bar baz'.replace('foo', 'baz').replace('bar', 'baz')
> baz baz baz
> after
> >>> 'foo bar baz'.replace(('foo', 'bar'), 'baz')
> baz baz baz

The usual current solution is to use `re.sub`:

    >>> re.sub("foo|bar", "baz", "foo bar baz")
    'baz baz baz'

or, for a general iterable of patterns

    re.sub("|".join(map(re.escape, patterns)), repl, string)


More information about the Python-ideas mailing list