13

我有一个带有转义数据的字符串,例如

escaped_data = '\\x50\\x51'
print escaped_data # gives '\x50\x51'

什么 Python 函数会取消它,所以我会得到

raw_data = unescape( escaped_data)
print raw_data # would print "PQ"
4

4 回答 4

20

您可以使用解码string-escape

>>> escaped_data = '\\x50\\x51'
>>> escaped_data.decode('string-escape')
'PQ'

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

从一个bytes对象:

>>> escaped_data = b'\\x50\\x51'
>>> escaped_data.decode("unicode_escape")
'PQ'

从 Unicodestr对象:

>>> import codecs
>>> escaped_data = '\\x50\\x51'
>>> codecs.decode(escaped_data, "unicode_escape")
'PQ'
于 2012-06-08T07:49:07.353 回答
7

您可以使用“unicode_escape”编解码器:

>>> '\\x50\\x51'.decode('unicode_escape')
u'PQ'

或者,'string-escape' 会给你一个经典的 Python 2 字符串(Python 3 中的字节):

>>> '\\x50\\x51'.decode('string_escape')
'PQ'
于 2012-06-08T07:48:29.173 回答
3

escaped_data.decode('unicode-escape')有帮助吗?

于 2012-06-08T07:48:34.593 回答
-4

尝试:

eval('"' + raw_data + '"')

它应该工作。

于 2012-06-08T07:48:15.500 回答