How to replace two things at once in a string?

When you need to swap variables, say x and y, a common pattern is to introduce a temporary variable t to help with the swap: t = x; x = y; y = t.

The same pattern can also be used with strings:

>>> # swap a with b
>>> 'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')
'oabmb'

This technique isn't new. It is described in PEP 378 as a way to convert between American and European style decimal separators and thousands separators (for example from 1,234,567.89 to 1.234.567,89. Guido has endorsed this as a reasonable technique.


If you are OK with two lines, this is more elegant.

d={'a':'b','b':'a'}
''.join(d[s] for s in "abaababbd" if s in d.keys())

import string
"abaababb".translate(string.maketrans("ab", "ba"))
# result: 'babbabaa'

Note that this only works for one-character substitutions.

For longer substrings or substitutions, this is a bit complex, but might work:

import re

def replace_all(repls, str):
    # return re.sub('|'.join(repls.keys()), lambda k: repls[k.group(0)], str)                                     
    return re.sub('|'.join(re.escape(key) for key in repls.keys()),
                  lambda k: repls[k.group(0)], str)                                     


text =  "i like apples, but pears scare me"
print replace_all({"apple": "pear", "pear": "apple"}, text)

Unfortunately this won't work if you include any regexp special characters you can't use regexps this way :(

(Thanks @TimPietzcker)

Tags:

Python

String