python - PyBytes_Type 和 PyString_Type 有什么区别

标签 python string unicode python-c-api

看来 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 ~ ?

如果可以,如何完成?

编辑:Python2 doc for 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/

相关文章:

python - 在哪里可以找到 py2exe 的好教程?

python - Kivy GridLayout 中的空 id 列表

python - Pandas .str.replace 和不区分大小写

jquery - 数组的值格式为 "item1,item2"。我希望它是 ["item1","item2"]。我应该怎么办?

javascript - 使用 Javascript 查找 Unicode 字符名称

python - 编写并行循环

python - 缓慢保存到 Django 数据库

c - C中的字符串分隔和格式化

javascript - 在希伯来语中搜索希伯来语悬音标记

Python:如何将 Windows 1251 转换为 Unicode?