[英]compatible python literals for python2 and python3
In python 3 I write 在python 3我写
s = '\u0300'
and I get a single unicode character, but that doesn't work in python2, I get a string of various characters. 并且我得到了一个unicode字符,但是在python2中不起作用,我得到了由各种字符组成的字符串。
python2 seems to want: python2似乎想要:
s = u'\u0300'
so that I must check sys.version_info
in order to know if I'm running python 2 or 3 and use the former or the latter accordingly. 因此,我必须检查
sys.version_info
才能知道我是否正在运行python 2或3,并相应地使用前者或后者。
Is there a way to write the assignment in a way that works in both versions? 有没有一种方法可以在两种版本中都可以工作的方式编写作业?
Python 3 (starting from 3.3 IIRC) supports u''
string literals. Python 3(从3.3 IIRC开始)支持
u''
字符串文字。 Or you can use 或者你可以使用
from __future__ import unicode_literals
to get Python3-compatible string literals in Python 2. This statement is no-op in Python 3. 在Python 2中获取与Python3兼容的字符串文字。在Python 3中,此语句是no-op。
The most compatible way is to use the six
module or a similar compatibility shim: 最兼容的方法是使用
six
模块或类似的兼容垫片:
import six
s = six.u('\u0300')
six
is available on PyPI, and is extremely broadly used and well-tested. PyPI上有
six
可用,并且使用极为广泛且经过了良好的测试。
Another alternative is: 另一种选择是:
from __future__ import unicode_literals
s = '\u0300'
But, this can conflict with a number of Python 2 expectations, that string items can contain bytes. 但是,这可能与许多Python 2期望冲突,即字符串项可以包含字节。 With
unicode_literals
on, string literals will be silently, almost magically upgraded to Unicode strings. unicode_literals
时,字符串文字将被静默化,几乎神奇地升级为Unicode字符串。 Python culture often favors explicit over implicit. Python文化通常倾向于显式而非隐式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.