python字节(一些_字符串,“UTF-8”)和str(一些_字符串,“UTF-8”)

2024-03-29 08:54:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将为python3编写的代码修改为python2.7,这样做的时候,由于这两个原因,我得到了一些错误

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

我的问题是:

是否遵循正确的方法来调整str(某些字符串'UTF-8')

a = str(some_string)

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

python3中介绍了如何将字节(一些_字符串,“UTF-8”)作为字节调整到python2.7。


Tags: and方法字符串代码string字节bytes错误
1条回答
网友
1楼 · 发布于 2024-03-29 08:54:09

python2中只需要some_stringstr(some_string)就可以了,因为some_string已经是一个ascii字符串,并且这两个操作都将其转换为类型str。 在Python3中,str类型与Python2中的unicode类型相同。

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

In Python 2, str and bytes are the same type:

bytes is str True In Python 3, the str type is Python 2's unicode type, which is the default encoding of all strings.

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

相关问题 更多 >