2013-10-15 29 views
5

下面是一个简单的测试。 repr似乎工作正常。但lenx for x in似乎并没有对Unicode文本在Python 2.6和2.7正确划分:python是否支持unicode超越基础多语种平面?

In [1]: u"" 
Out[1]: u'\U0002f920\U0002f921' 

In [2]: [x for x in u""] 
Out[2]: [u'\ud87e', u'\udd20', u'\ud87e', u'\udd21'] 

好消息是Python的3.3做正确的事™。

Python 2.x系列有没有希望?

回答

10

是的,只要你编译你的Python与广泛的unicode支持。

默认情况下,Python仅使用窄Unicode支持构建。支持与广泛支持:

./configure --enable-unicode=ucs4 

您可以验证使用什么配置通过测试sys.maxunicode

import sys 
if sys.maxunicode == 0x10FFFF: 
    print 'Python built with UCS4 (wide unicode) support' 
else: 
    print 'Python built with UCS2 (narrow unicode) support' 

广泛的构建将使用UCS4字符所有 Unicode值,增加一倍,这些内存使用情况。 Python 3.3切换到可变宽度值;只有足够的字节用于表示当前值中的所有字符。

快速演示显示出广泛的构建正确处理您的样品Unicode字符串:

$ python2.6 
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) 
[GCC 4.4.5] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import sys 
>>> sys.maxunicode 
1114111 
>>> [x for x in u'\U0002f920\U0002f921'] 
[u'\U0002f920', u'\U0002f921'] 
+1

哪种编码不使用3.3? –

+1

@DavidHeffernan:参见[PEP 393](http://docs.python.org/3/whatsnew/3.3.html#pep-393);直到UCS4,如果所有字符的2个LSB字节都为0,则下降到UCS2,如果所有字符的剩余LSB为0,那么直到拉丁-1。 –

+0

谢谢。看起来非常狂野。维护字符串的并行副本。有趣的是,他们选择了与负载相关的编码 –