在Python 2和3中有效的Unicode字面量

39 投票
2 回答
10866 浏览
提问于 2025-04-16 21:06

我有一个Python脚本,我希望它在Python 3.2和2.7上都能运行,这样更方便。

有没有办法让Unicode字符串在这两个版本中都能用呢?比如:

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

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

2 个回答

0

在3.0、3.1和3.2版本中:

from __future__ import unicode_literals

来源: ubershmekel,来自提问。查看修订版4以获取原始内容。

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

你可以这样使用它:

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

撰写回答