13
votes

I have a string with escaped data like

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

What Python function would unescape it so I would get

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

4 Answers

17
votes

You can decode with string-escape.

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

In Python 3.0 there's no string-escape, but you can use unicode_escape.

From a bytes object:

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

From a Unicode str object:

>>> import codecs
>>> escaped_data = '\\x50\\x51'
>>> codecs.decode(escaped_data, "unicode_escape")
'PQ'
7
votes

You could use the 'unicode_escape' codec:

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

Alternatively, 'string-escape' will give you a classic Python 2 string (bytes in Python 3):

>>> '\\x50\\x51'.decode('string_escape')
'PQ'
3
votes

escaped_data.decode('unicode-escape') helps?

-4
votes

Try:

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

It should work.