看来 Python 2 有 PyString_Type,而 Python 3 有 PyBytes_Type
幕后发生了什么?
我正在编写一个 C++ 包装器(当前正在包装 Python3,但我希望稍后添加 Python2 支持),并且我刚刚完成了包装字符串的任务。
2 和 3 都为字节字符串和 Unicode 字符串提供单独的支持,但它们只是做了一些重命名,这是正确的吗?
如果是这样,那么这个表正确吗?:
Py2 byte-string ~ PyString_Type Py2 Unicode-string ~ PyUnicode_Type
Py3 byte-string ~ PyBytes_Type Py3 Unicode-string ~ ?
如果可以,如何完成?
These functions have been renamed to PyBytes_ in Python 3.x*. Unless otherwise noted, the PyBytes functions available in 3.x are aliased to their PyString_* equivalents to help porting.
最佳答案
在 Python 2 中,str
包含字节(且类型 bytes == str
),unicode
包含 Unicode 字符串。因此2.x有效地分为三种类型。
在Python 3中,bytes
包含字节,str
包含Unicode字符串。 3.x 中的 str
类型是 2.x 的 unicode
类型。因此3.x实际上有两种类型。这是您应该采用的概念方法,任何 2.x 相关的工作也应该以这种方式分离 Unicode 字符串和字节。
基于this section在文档中,这意味着 PyUnicode
在 2.x 和 3.x 中都用于 Unicode 字符串。 PyBytes
用于两者中的字节字符串,并且 PyString
类型仅在 Python 2.x 中有意义。
关于python - PyBytes_Type 和 PyString_Type 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27460578/