简体   繁体   English

Python:unescape“\\ xXX”

[英]Python: unescape “\xXX”

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 什么Python函数会覆盖它,所以我会得到

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

You can decode with string-escape . 您可以使用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 . Python 3.0中没有string-escape ,但您可以使用unicode_escape

From a bytes object: 从一个bytes对象:

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

From a Unicode str object: 从Unicode str对象:

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

You could use the 'unicode_escape' codec: 你可以使用'unicode_escape'编解码器:

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

Alternatively, 'string-escape' will give you a classic Python 2 string (bytes in Python 3): 或者,'string-escape'将为您提供经典的Python 2字符串(Python 3中的字节):

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

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

Try: 尝试:

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

It should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM