Python:unescape"\ xXX"

Jak*_* M. 13 python

我有一个字符串转义的数据

escaped_data = '\\x50\\x51'
print escaped_data # gives '\x50\x51'
Run Code Online (Sandbox Code Playgroud)

什么Python函数会覆盖它,所以我会得到

raw_data = unescape( escaped_data)
print raw_data # would print "PQ"
Run Code Online (Sandbox Code Playgroud)

Chr*_*tts 17

你可以用解码string-escape.

>>> escaped_data = '\\x50\\x51'
>>> escaped_data.decode('string-escape')
'PQ'
Run Code Online (Sandbox Code Playgroud)

Python 3.0中没有string-escape,但你可以使用unicode_escape.

从一个bytes对象:

>>> escaped_data = b'\\x50\\x51'
>>> escaped_data.decode("unicode_escape")
'PQ'
Run Code Online (Sandbox Code Playgroud)

从Unicode str对象:

>>> import codecs
>>> escaped_data = '\\x50\\x51'
>>> codecs.decode(escaped_data, "unicode_escape")
'PQ'
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 7

你可以使用'unicode_escape'编解码器:

>>> '\\x50\\x51'.decode('unicode_escape')
u'PQ'
Run Code Online (Sandbox Code Playgroud)

或者,'string-escape'将为您提供经典的Python 2字符串(Python 3中的字节):

>>> '\\x50\\x51'.decode('string_escape')
'PQ'
Run Code Online (Sandbox Code Playgroud)