如何在py2和py3中都能工作的方式将对象转换为Unicode?

2024-04-29 11:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试修复Python库中的一个bug,当我试图将一个对象转换为string时会发生这种错误。在

str(obj)      # fails on py2 when the object return unicode
unicode(obj)  # works perfectly on py2 but fails on py3 

Tags: the对象objstringreturnobjecton错误
3条回答

您可以使用%s格式来获得2.7中的unicode()和3.5中的str(),只要您导入unicode_literals,每个人都应该这样做。在

我发现这个技巧非常有用,它不需要到处导入compat库。在

PY 2.7倍

>>> from __future__ import unicode_literals
>>> "%s" % 32
u'32'  (<type 'unicode'>)

第3.5页

^{pr2}$

在这里添加这个,因为这是我在寻找six.text_type(value)或其他compat库之外的东西时在google中出现的第一个结果。在

由于在从Python2迁移到Python3时,unicode被转换为标准的str类型(其中str会变成{}),所以在python2和python3中运行时,解决这个问题的一种方法是在python3中运行时将unicode定义为与{}等效。这通常是在需要同时支持这两个Python版本的库中完成的,可以在^{}^{}(其中包括更全面的兼容性层)找到示例。任何对该库的内部调用都将在需要时引用该类型,以确保在检查不变量/断言、强制转换等时需要bytes或{}。在

Django有一个很好的解决方案,他们为用户提供了一个可以应用于类的decorator。在

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。(请注意代码许可证!)在

相关问题 更多 >