3 回答
TA贡献1804条经验 获得超2个赞
你必须使用unicode_escape:
>>> b"\\123omething special".decode('unicode_escape')
如果你从一个str对象开始(相当于python 2.7 unicode),你需要首先编码为字节,然后解码unicode_escape。
如果您需要字节作为最终结果,则必须再次编码.encode('latin1')为合适的编码(例如,如果您需要保留文字字节值;前256个Unicode代码点映射1对1)。
您的示例实际上是带有转义的UTF-16数据。解码unicode_escape,返回以latin1保留字节,然后从utf-16-le(没有BOM的UTF 16小端)解码:
>>> value = b's\\000u\\000p\\000p\\000o\\000r\\000t\\000@\\000p\\000s\\000i\\000l\\000o\\000c\\000.\\000c\\000o\\000m\\000'
>>> value.decode('unicode_escape').encode('latin1') # convert to bytes
b's\x00u\x00p\x00p\x00o\x00r\x00t\x00@\x00p\x00s\x00i\x00l\x00o\x00c\x00.\x00c\x00o\x00m\x00'
>>> _.decode('utf-16-le') # decode from UTF-16-LE
'support@psiloc.com'
TA贡献1784条经验 获得超7个赞
你不能使用unicode_escape字节字符串(或者更确切地说,你可以,但它并不总是返回与string_escapePython 2 相同的东西) - 小心!
此函数实现string_escape使用正则表达式和自定义替换逻辑。
def unescape(text):
regex = re.compile(b'\\\\(\\\\|[0-7]{1,3}|x.[0-9a-f]?|[\'"abfnrt]|.|$)')
def replace(m):
b = m.group(1)
if len(b) == 0:
raise ValueError("Invalid character escape: '\\'.")
i = b[0]
if i == 120:
v = int(b[1:], 16)
elif 48 <= i <= 55:
v = int(b, 8)
elif i == 34: return b'"'
elif i == 39: return b"'"
elif i == 92: return b'\\'
elif i == 97: return b'\a'
elif i == 98: return b'\b'
elif i == 102: return b'\f'
elif i == 110: return b'\n'
elif i == 114: return b'\r'
elif i == 116: return b'\t'
else:
s = b.decode('ascii')
raise UnicodeDecodeError(
'stringescape', text, m.start(), m.end(), "Invalid escape: %r" % s )
return bytes((v, ))
result = regex.sub(replace, text)添加回答
举报
