我有:b'{"street":"Grossk\\xc3\\xb6lnstra\\xc3\\x9fe"}'
我需要:'{"street": "Grosskölnstraße"}'
我试过:
s.decode('utf8'): # '{"street":"Grossk\\xc3\\xb6lnstra\\xc3\\x9fe"}'
s.decode('unicode_escape'): # '{"street":"GrosskölnstraÃ\x9fe"}'
正确的做法是什么?
请您参考如下方法:
那是.. 你那里一团糟。这看起来像是作为 Python 字节转义序列嵌入的 UTF-8 字节。
没有编解码器会再次产生字节作为输出;您需要使用 unicode_escape 序列,然后重新编码为 Latin-1 以返回 UTF8 字节,然后解码为 UTF-8:
s.decode('unicode_escape').encode('latin1').decode('utf8')
演示:
>>> s = b'{"street":"Grossk\\xc3\\xb6lnstra\\xc3\\x9fe"}'
>>> s.decode('unicode_escape').encode('latin1').decode('utf8')
'{"street":"Grosskölnstraße"}'
另一种选择是仅针对正则表达式中的 \x[hexdigits]{3} 模式;如果特定数据不是由错误的 Python 脚本生成的,这可能是更可靠的选择:
import re
from functools import partial
escape = re.compile(rb'\\x([\da-f]{2})')
repair = partial(escape.sub, lambda m: bytes.fromhex(m.group(1).decode()))
repair() 返回一个 bytes 对象:
>>> repair(s)
b'{"street":"Grossk\xc3\xb6lnstra\xc3\x9fe"}'
>>> repair(s).decode('utf8')
'{"street":"Grosskölnstraße"}'
