由于Python2.2和佩普261,Python可以在“窄”或“宽”模式下构建,这会影响“字符”的定义,即“Python字符串的可寻址单元”。
窄构建中的字符看起来类似于UTF-16代码单元:
>>> a = u'\N{MAHJONG TILE GREEN DRAGON}'
>>> a
u'\U0001f005'
>>> len(a)
2
>>> a[0], a[1]
(u'\ud83c', u'\udc05')
>>> [hex(ord(c)) for c in a.encode('utf-16be')]
['0xd8', '0x3c', '0xdc', '0x5'](以上似乎不同意http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python https://stackoverflow.com/questions/1838170/what-is-internal-representation-of-string-in-python-3-x的观点,即狭隘的构建使用UCS-2,而不是UTF-16。非常有趣)
Python3.0是否保留了这种区别?还是所有Python3的构建都很宽?
(我听说过佩普393在3.3中改变了字符串的内部表示形式,但这与3.0 ~3.2无关。)
发布于 2013-02-09 20:02:51
是的,从3.0到3.2都有。Windows使用窄生成,而(大多数) Unix使用宽生成。
在Windows上使用Python3.2:
>>> a = '\N{MAHJONG TILE GREEN DRAGON}'
>>> len(a)
2
>>> a
''虽然在使用3.3+的情况下,这种行为是预期的:
>>> a = '\N{MAHJONG TILE GREEN DRAGON}'
>>> len(a)
1
>>> a
'\U0001f005'
>>> print(a)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(a)
UnicodeEncodeError: 'UCS-2' codec can't encode character '\U0001f005'
in position 0: Non-BMP character not supported in TkUCS-2编解码器在Tk上使用(我使用的是空闲,终端可能会显示另一个错误)。
https://stackoverflow.com/questions/14790708
复制相似问题