【问题标题】:UTF-8 encoding in str type Python 2str 类型 Python 2 中的 UTF-8 编码
【发布时间】: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] 时会发生什么?

标签: python utf-8 base64


【解决方案1】:

你想decode,而不是encode字节串。

可以这样想:一个 Unicode 字符串被编码成字节,这些字节被进一步编码成 base64。

要反转这一点,您需要以相反的顺序反转两种编码。

但是,您显示的示例绝对不是有效的 UTF-8 字节字符串 - 单独的 0xE3 不是有效的 UTF-8 编码。最有可能的是,Unicode 字符串是使用 Latin-1 或相关编码进行编码的(样本太小,无法确定这一点;其他常见的候选者是丑陋的 Windows 代码页 CP1252 和 Latin-9)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    相关资源
    最近更新 更多