Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: unescape "\xXX"

Tags:

python

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"
like image 380
Jakub M. Avatar asked Jun 08 '12 07:06

Jakub M.


2 Answers

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'
like image 190
Christian Witts Avatar answered Oct 31 '22 15:10

Christian Witts


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'
like image 7
Martijn Pieters Avatar answered Oct 31 '22 15:10

Martijn Pieters