If your input value is a str
string, use codecs.decode()
to convert:
import codecs
codecs.decode(raw_unicode_string, 'unicode_escape')
If your input value is a bytes
object, you can use the bytes.decode()
method:
raw_byte_string.decode('unicode_escape')
Demo:
>>> import codecs
>>> codecs.decode('\x89\n', 'unicode_escape')
'x89
'
>>> b'\x89\n'.decode('unicode_escape')
'x89
'
Python 2 byte strings can be decoded with the 'string_escape'
codec:
>>> import sys; sys.version_info[:2]
(2, 7)
>>> '\x89\n'.decode('string_escape')
'x89
'
For Unicode literals (with a u
prefix, e.g. u'\x89\n'
), use 'unicode_escape'
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…