【问题标题】:Unicode literals that work in python 3 and 2在 python 3 和 2 中工作的 Unicode 文字
【发布时间】:2011-10-01 07:58:16
【问题描述】:

所以我有一个 python 脚本,为了方便起见,我更喜欢在 python 3.2 和 2.7 上工作。

有没有办法让 unicode 文字同时适用于两者?例如

#coding: utf-8
whatever = 'שלום'

上面的代码在 python 2.x (u'') 中需要一个 unicode 字符串,而在 python 3.x 中,小的 u 会导致语法错误。

【问题讨论】:

  • @ubershmekel 您会推荐哪种解决方案?你的还是接受答案的?
  • 我建议使用u'',因为它现在在 python 3.3 中得到支持

标签: python python-3.x unicode python-2.x unicode-literals


【解决方案1】:

在 3.0、3.1 和 3.2 中:

from __future__ import unicode_literals

来源ubershmekel,在问题中。原文见revision 4

【讨论】:

    【解决方案2】:

    编辑 - 自 Python 3.3 起,u'' 文字再次起作用,因此不再需要 u() 函数。

    最好的选择是创建一个方法,在 Python 2 中从字符串对象创建 unicode 对象,但在 Python 3 中单独保留字符串对象(因为它们已经是 unicode)。

    import sys
    if sys.version < '3':
        import codecs
        def u(x):
            return codecs.unicode_escape_decode(x)[0]
    else:
        def u(x):
            return x
    

    然后你会像这样使用它:

    >>> print(u('\u00dcnic\u00f6de'))
    Ünicöde
    >>> print(u('\xdcnic\N{Latin Small Letter O with diaeresis}de'))
    Ünicöde
    

    【讨论】:

    • 如果您删除了第二部分,我会接受您的回答,因为它不适用于包含实际未转义 unicode 的 unicode 文字。编辑 - 如果您在答案中澄清细微差别,我会很高兴。
    • 您不传入 unicode 文字,而是传入字符串文字,这就是它的全部意义所在。我试图澄清这一点。
    • “不需要 u() 函数。”,为了支持仍在使用 Python 3.2 的人,需要它。
    • “unicode 文字”不是“字符串文字”的类型吗?
    • 在 Python 3 中它们是一样的,在 Python 2 中它们不是。
    猜你喜欢
    • 2016-01-06
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    相关资源
    最近更新 更多