Switch chars with regex
Question: Say I have something like `s='abaabbab'`. Is it possible to change this to
`s='babbaaba'` using regex? I mainly want to know if this is possible, not if
it is reasonable.

I thought perhaps one of these would work (having previously imported
[`re`](http://docs.python.org/2/library/re.html)):

    
    
    s='ab'
    re.sub('a|b',lambda x:['b','a'][x=='a'],s)
    #or maybe
    re.sub(r'a|b',lambda x:['b','a'][x=='b'],s)
    

But they just result in `'bb'`.

* * *

I know I could replace all `a`'s with `c`'s, then replace all `b`'s with
`a`'s, then replace all `c`'s with `b`'s, but this seems so long.

[gnibbler suggests this:](http://stackoverflow.com/a/3463853/1896169)

    
    
    from string import maketrans
    trans_table = maketrans(".-a","-.A")
    "foo-bar.".translate(trans_table)
    

But I doesn't seem to work in python 3.


Answer: > Say I have something like s='abaabbab'. Is it possible to change this to
> s='babbaaba' using regex? I mainly want to know if this is possible, not if
> it is reasonable.

Yes - but you should use the correct form of `str.translate` as pointed out by
falsetru for this task...

    
    
    import re
    
    s = 'abaabbab'
    print re.sub('[ab]', lambda L: {'a': 'b', 'b': 'a'}[L.group()], s)
    # babbaaba
    

How this is works is by looking for characters (those defined between the
`[]`) and upon a match, calls the replacement function (here defined by a
lambda) which looks for the suitable replacement character using a dictionary.

