![](/img/trans.png)
[英]How to define a binary string in Python in a way that works with both py2 and py3?
[英]How to convert an object to Unicode in a way that works in both py2 and py3?
我正在尝试修复Python库中的错误,该错误在我尝试将对象转换为字符串时发生。
str(obj) # fails on py2 when the object return unicode
unicode(obj) # works perfectly on py2 but fails on py3
由于从Python 2移至Python 3时unicode
转换为标准str
类型( str
转换为bytes
),因此以在Python 2和3中运行的方式解决此问题的一种方法是将unicode
定义为等效到str
在Python 3.运行时,这是在需要支持这两个Python版本库通常完成,实例可以在以下网址找到oauthlib.common
或requests.compat
(其包括一个更全面的兼容性层)。 每当他们需要确保他们需要在内部对该库的任何调用将引用该类型bytes
或str
为不变量/断言,铸造等检查时。
Django为此提供了一个简洁的解决方案,他们为用户提供了可以应用于该类的装饰器。
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if six.PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
虽然这取决于python库6。 (请注意代码许可证!)
您可以使用%s
格式在2.7中获得unicode()并在3.5中获得str(),只要您导入unicode_literals
,每个人都应该这样做。
我发现这个技巧很有帮助,不需要到处都导入compat库。
PY 2.7倍
>>> from __future__ import unicode_literals
>>> "%s" % 32
u'32' (<type 'unicode'>)
PY 3.5
>>> ("%s" % (42)).__class__
<class 'str'>
在此处添加此内容是因为它是我寻找除six.text_type(value)
或其他compat库之外的其他东西时在google中出现的第一个结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.