How to replace two things at once in a string?

Say I have a string, "ab".

I want to replace "a" with "b" and "b" with "a" in one swoop.

So in the end, the string should be "ba" and not "aa" or "bb" and not use more than one line. Is this doable?


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.


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)