I would like to turn this string:
a = '\\a'
b = '\a'
The character '\a' is the ASCII BEL character, chr(7).
To do the conversion in Python 2:
from __future__ import print_function a = '\\a' c = a.decode('string-escape') print(repr(a), repr(c))
And for future reference, in Python 3:
a = '\\a' b = bytes(a, encoding='ascii') c = b.decode('unicode-escape') print(repr(a), repr(c))
This gives identical output to the above snippet.
In Python 3, if you were working with bytes objects you'd do something like this:
a = b'\\a' c = bytes(a.decode('unicode-escape'), 'ascii') print(repr(a), repr(c))
As Antti Haapala mentions, this simple strategy for Python 3 won't work if the source string contains unicode characters too. In tha case, please see his answer for a more robust solution.