如何使用反斜杠 x \x 代码解码 ascii 字符串

how to decode an ascii string with backslash x \x codes

我正在尝试从巴西葡萄牙语文本解码:

'Demais Subfun\xc3\xa7\xc3\xb5es 12'

应该是

'Demais Subfunções 12'

>> a.decode('unicode_escape')
>> a.encode('unicode_escape')
>> a.decode('ascii')
>> a.encode('ascii')

都给:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13:
ordinal not in range(128)

另一方面,这给出了:

>> print a.encode('utf-8')
Demais Subfun├â┬º├â┬Áes 12

>> print a
Demais Subfunções 12

您有 ASCII 编码的二进制数据。 \xhh 代码点表示您的数据是使用不同的编解码器编码的,并且您看到 Python 生成数据 using the repr() function 表示 重新用作 Python 文字,可以准确地让您重新创建完全相同的值。这种表示在调试程序时非常有用。

换句话说,\xhh 转义序列代表单个字节,而 hh 是该字节的十六进制值。您有 4 个十六进制值 C3、A7、C3 和 B5 的字节,它们不映射到可打印的 ASCII 字符,因此 Python 使用 \xhh 表示法。

您改为使用 UTF-8 数据,将其解码为:

>>> 'Demais Subfun\xc3\xa7\xc3\xb5es 12'.decode('utf8')
u'Demais Subfun\xe7\xf5es 12'
>>> print 'Demais Subfun\xc3\xa7\xc3\xb5es 12'.decode('utf8')
Demais Subfunções 12

C3 A7字节一起编码U+00E7 LATIN SMALL LETTER C WITH CEDILLA, while the C3 B5 bytes encode U+00F5 LATIN SMALL LETTER O WITH TILDE.

ASCII 恰好是 UTF-8 编解码器的一个子集,这就是为什么所有其他字母都可以在 Python repr() 输出中这样表示的原因。