【发布时间】:2018-07-11 14:38:32
【问题描述】:
我有一个 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 中执行此操作?
【问题讨论】:
-
可能解码为 Latin-1
-
当你
print decoded_str[x:y]时会发生什么?