【问题标题】:Why do Mac OS X python versus CentOS Linux python have different interpretations of \U escapes in strings?为什么 Mac OS X python 与 CentOS Linux python 对字符串中的 \U 转义有不同的解释?
【发布时间】:2012-06-08 23:34:45
【问题描述】:

两个 python 解释器会话。第一个来自 CentOS 上的 python。第二个来自 Mac OS X 10.7 上的内置 python。为什么第二个会话会从 \U 转义序列中创建长度为 2 的字符串,并随后出错?

$ python
Python 2.6.6 (r266:84292, Dec  7 2011, 20:48:22) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> u'\U00000020'
u' '
>>> u'\U00000065'
u'e'
>>> u'\U0000FFFF'
u'\uffff'
>>> u'\U00010000'
u'\U00010000'
>>> len(u'\U00010000')
1
>>> ord(u'\U00010000')
65536

$ python
Python 2.6.7 (r267:88850, Jul 31 2011, 19:30:54) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> u'\U00000020'
u' '
>>> u'\U00000065'
u'e'
>>> u'\U0000FFFF'
u'\uffff'
>>> u'\U00010000'
u'\U00010000'
>>> len(u'\U00010000')
2
>>> ord(u'\U00010000')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found

【问题讨论】:

    标签: python macos unicode centos


    【解决方案1】:

    我对此完全不确定,但可能是您的 Mac OS X 系统使用了 Python 的“窄构建”,它表示 unicode,只有 16 位用于 unicode 的内部编码,并表示 unicode 代码点以上 2**16 作为字符对(这将解释len(u'\U00010000') == 2

    在 OS X 上尝试unichr(0x10000),看看您是否收到有关窄构建的错误。另请参阅What encoding do normal python strings use?,尤其是 IVH 的回答。

    即使系统上的默认 python 使用窄版本,也可以重新编译 python 以使用宽版本。

    【讨论】:

    • 好收获。大概就是这样。也见这篇文章:wordaligned.org/articles/narrow-python
    • 这是正确的答案。我收到有关“窄 Python 构建”的错误,并且 sys.maxunicode 在 Mac OS X 上返回 65535。
    • @user802500:我可能有误会,但在这种情况下,Mac OS 不是具有狭窄的构建吗?
    • 你是对的。当我回答帖子时,我已经翻转了哪个操作系统正在做什么。现在已编辑。
    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2012-09-28
    相关资源
    最近更新 更多