在python 3和2中工作的Unicode文字

ube*_*kel 37 python unicode python-2.x python-3.x unicode-literals

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

有没有办法让unicode文字在两者中都有效?例如

#coding: utf-8
whatever = '????'
Run Code Online (Sandbox Code Playgroud)

上面的代码需要python 2.x(u'')中的unicode字符串和python 3.x中的小'u'导致语法错误.

无论如何我找到了答案,我所需要的只是:

#coding: utf-8
whatever = '????'
Run Code Online (Sandbox Code Playgroud)

由于https://meta.stackexchange.com/questions/49922/should-i-continue-adding-a-question-if-i-have-found-the-answer-myself,我仍然在发布这个问题

对于好奇,我正在努力:http://code.google.com/p/pytitle/

Len*_*bro 27

编辑 - 从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
Run Code Online (Sandbox Code Playgroud)

然后你会像这样使用它:

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

  • "u()函数不是必需的.",为了支持仍在使用Python 3.2的人,需要它. (2认同)