python 字节(some_string, 'UTF-8') 和 str(some_string, 'UTF-8')

rah*_*mar 8 python string encoding utf-8 character-encoding

我想将为 python3 编写的代码改编为 python2.7,同时这样做我因为这两个而出错

bytes(some_string, 'UTF-8') 和 str(some_string, 'UTF-8')

我的问题:

遵循正确的方法来适应 str(some_string, 'UTF-8')

a = str(some_string)

a = a.encode('UTF-8')

以及如何将 bytes(some_string, 'UTF-8') 适配到 python2.7,因为 python3 中引入了字节。

Rom*_*man 5

只是some_stringstr(some_string)将在 python2 中执行,因为some_string它已经是一个 ascii 字符串,并且这两个操作都将其转换为 type str。在 python 3 中 str 类型与 python 2 中的 unicode 类型相同。

请阅读此答案,我认为它很好地回答了您的问题。

在 Python 2 中, str 和 bytes 是相同的类型:

bytes 是 str True 在 Python 3 中, str 类型是 Python 2 的 unicode 类型,它是所有字符串的默认编码。

换句话说,bytes(some_string, 'UTF-8')在 python 2 中只是str(some_string), 因为str 一个字节串。