Python 3.x中字符串的内部表示是什么

2024-04-26 07:56:40 发布

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

在Python3.x中,字符串由Unicode序号项组成。(请参阅下面的语言引用中的引号。)Unicode字符串的内部表示形式是什么?是UTF-16吗?

The items of a string object are Unicode code units. A Unicode code unit is represented by a string object of one item and can hold either a 16-bit or 32-bit value representing a Unicode ordinal (the maximum value for the ordinal is given in sys.maxunicode, and depends on how Python is configured at compile time). Surrogate pairs may be present in the Unicode object, and will be reported as two separate items.


Tags: andofthe字符串instringobjectis
3条回答

Python 2.X和3.X之间的Unicode内部表示没有变化

肯定不是UTF-16。UTF anything是面向字节的外部表示。

每个代码单元(字符、代理项等)都被分配了一个范围(0,2**21)内的数字。这被称为“序数”。

真的,你引用的文件说明了一切。大多数Python二进制文件都使用16位序数,这将限制您使用基本的多语言平面(“BMP”),除非您想和代理对象混在一起(如果找不到您的头发衬衫,而且您的指甲床已经被除锈,那么使用这些序数很方便)。对于使用完整的Unicode曲目,您更喜欢“宽构建”(32位宽)。

简单地说,unicode对象的内部表示是16位无符号整数数组,或32位无符号整数数组(仅使用21位)。

在Python 3.3及更高版本中,字符串的内部表示将取决于字符串,可以是拉丁语1、UCS-2或UCS-4中的任何一个,如PEP 393中所述。

对于以前的Python,内部表示依赖于Python的构建标志。Python可以用标志值--enable-unicode=ucs2--enable-unicode=ucs4构建。ucs2构建实际上是use UTF-16 as their internal representation,而ucs4构建使用UCS-4/UTF-32。

内部表示将在实现PEP 393的Python 3.3中更改。新的表示法将选择ascii、拉丁语-1、utf-8、utf-16、utf-32中的一个或多个,通常试图得到一个紧凑的表示法。

只有在与遗留api(那些api只存在于windows上,其中wchar_t是两个字节)交谈时,才会执行到代理项对的隐式转换;Python字符串将被保留。这是release notes

相关问题 更多 >