Python中的Unicode

2024-04-19 17:00:33 发布

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

在Python 2.7的文档中,关于Unicode的三条规则描述如下:

If the code point is <128, it’s represented by the corresponding byte value.

If the code point is between 128 and 0x7ff, it’s turned into two byte values between 128 and 255.

Code points >0x7ff are turned into three- or four-byte sequences, where each byte of the sequence is between 128 and 255.

然后我做了一些测试:

>>>> unichr(40960)

u'\ua000'

>>> ord(u'\ua000')

40960

在我看来,40960是一个代码点>;0x7ff,所以它应该被转换成三个或四个字节的序列,其中序列的每个字节都在128到255之间,但是它只会变成两个字节的序列,并且u'\a000'中的值'00'小于128,与上面提到的规则不匹配。为什么?在

另外,我发现了更多的Unicode字符,比如u'\u1234'等等,我发现其中的值(“12”&;“34”)也低于128,但根据前面提到的理论,它们不应该低于128。还有什么我丢的理论吗?在

谢谢你的回答。在


Tags: andtheif字节is规则unicodecode
3条回答

这些规则只适用于UTF-8。Python在内部使用UCS-2或UCS-4,它们具有固定的大小。在

"The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"

... and the value '00' in u'\a000' is lower than 128, not matched with the rules mentioned above.

我甚至不想知道你为什么认为他们可以这样分开。。。在

你的引语显然来自Unicode HOWTO(你真的应该告诉我们它来自哪里,如果可能的话还可以提供一个链接)并描述UTF-8。它并没有声称Python 2.7就是这样表示Unicode字符的,事实上,它却恰恰相反:

Under the hood, Python represents Unicode strings as either 16- or 32-bit integers, depending on how the Python interpreter was compiled.

in python2.7's documentation, three rules about unicodes are described as follows:

这是对UTF-8编码的描述。在

Then I made some tests about it:

\ua000是表示Unicode字符的转义序列。a000是数字代码位值的十六进制表示。它与UTF-8编码无关。在

当使用UTF-8编码显式地对unicode字符串进行编码时,可以得到UTF-8编码。在

相关问题 更多 >