The character '\ a' is the ASCII BEL character, chr (7).
Performing a conversion in Python 2:
from __future__ import print_function a = '\\a' c = a.decode('string-escape') print(repr(a), repr(c))
Output
'\\a' '\x07'
And for future use 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 byte objects, you would do something like this:
a = b'\\a' c = bytes(a.decode('unicode-escape'), 'ascii') print(repr(a), repr(c))
Output
b'\\a' b'\x07'
As Antti Haapala mentions, this simple strategy for Python 3 will not work if the original string contains Unicode characters. In this case, please see His answer for a more reliable solution.
source share