14

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"
Jakub M.
  • 32,471
  • 48
  • 110
  • 179

4 Answers4

21

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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christian Witts
  • 11,375
  • 1
  • 33
  • 46
  • How do you do this in Python3? – vy32 Feb 11 '13 at 20:35
  • You can use `unicode_escape`, for `bytes` object, is the same... for `str` objects you can do: `import codecs; codecs.decode('\\x50\\51', "unicode_escape")`... I edited the answer, can someone peer review it? – berdario Jun 17 '13 at 20:10
7

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'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

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

iMom0
  • 12,493
  • 3
  • 49
  • 61
-5

Try:

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

It should work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marcus
  • 6,701
  • 4
  • 19
  • 28