我有一个 Python 2.7 代码,它从服务器检索 base64 编码的响应。此响应使用base64模块(b64decode/decodestring函数,返回str)解码。其解码内容具有原始字符串的 Unicode 代码点。
我需要将这些 Unicode 代码点转换为 UTF-8。
原始字符串有一个子字符串内容“Não”。当我解码响应的字符串时,它显示:
>>> encoded_str = ... # server response
>>> decoded_str = base64.b64decode(encoded_str)
>>> type(decoded_str)
<type 'str'>
>>> decoded_str[x:y]
'N\xe3o'
当我尝试编码为 UTF-8 时,会导致错误为
>>> (decode_str[x:y]).encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 2: ordinal not in range(128)
但是,当此字符串以 Unicode 类型手动编写时,我可以正确地将其转换为所需的 UTF-8 字符串。
>>> test_str = u'N\xe3o'
>>> test.encode('utf-8')
'N\xc3\xa3o'
我必须从服务器检索此响应并正确生成可以打印为“Não”的 UTF-8 字符串,我该如何在 Python 2 中执行此操作?