繁体   English   中英

Python 为单个 Unicode 字符串返回长度为 2

[英]Python returns length of 2 for single Unicode character string

在 Python 2.7 中:

In [2]: utf8_str = '\xf0\x9f\x91\x8d'
In [3]: print(utf8_str)
👍
In [4]: unicode_str = utf8_str.decode('utf-8')
In [5]: print(unicode_str)
👍 
In [6]: unicode_str
Out[6]: u'\U0001f44d'
In [7]: len(unicode_str)
Out[7]: 2

由于unicode_str只包含一个 unicode 代码点 (0x0001f44d),为什么len(unicode_str)返回 2 而不是 1?

您的 Python 二进制文件是使用 UCS-2 支持(版本)编译的,并且 BMP(基本多语言平面)之外的任何内容在内部都使用代理对表示。

这意味着在要求长度时,此类代码点显示为 2 个字符。

如果这很重要( ./configure --enable-unicode=ucs4将启用它),您将不得不重新编译您的 Python 二进制文件以使用 UCS-4,或者升级到 Python 3.3 或更高版本,其中Python 的 Unicode 支持被彻底修改以使用一种可变宽度的 Unicode 类型,可根据包含的代码点的要求在 ASCII、UCS-2 和 UCS-4 之间切换。

在 Python 2.7 和 3.0 - 3.2 版本上,您可以通过检查sys.maxunicode来检测您的构建类型; 对于窄的 UCS-2 构建, 1114111 == 0x10FFFF2^16-1 == 65535 == 0xFFFF ,对于宽的 UCS-4 构建, 1114111 == 0x10FFFF 在 Python 3.3 及更高版本中,它始终设置为 1114111。

演示:

# Narrow build
$ bin/python -c 'import sys; print sys.maxunicode, len(u"\U0001f44d"), list(u"\U0001f44d")'
65535 2 [u'\ud83d', u'\udc4d']
# Wide build
$ python -c 'import sys; print sys.maxunicode, len(u"\U0001f44d"), list(u"\U0001f44d")'
1114111 1 [u'\U0001f44d']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM