繁体   English   中英

等同于适用于 Python 2.7 和 3.x 的 unicode() 函数?

[英]Equivalent to unicode() function that works with both Python 2.7 and 3.x?

我正在尝试修改一些旧代码以使其可用于 Python 2 和 3。我正在使用6 个包来完成这项任务。

如果我在 2.7 中有u'abc' ,我可以使用Six.u()函数并将其替换为six.u('abc')以使其在 2.7 和 3.x 中都能工作。

我如何做类似的事情:

  • unicode(value, errors='ignore', encoding='utf-8')

3.x 中没有unicode函数,我不能只用str替换它,因为这会改变 2.7 中的含义。

  • if isinstance(value, basestring): # do something

3.x 中没有basestring并且我不能在不改变含义的情况下用str替换它。

当然,我可以使用带有six.PY2six.PY3py2/3 检查来运行两个版本之一,但有更好的方法吗?

要回答问题的第二部分,您可以将if isinstance(value, basestring):替换为six.string_types

import six
if isinstance(value, six.string_types):
    pass

要回答第一部分,我首先建议将其放在代码的顶部:

from __future__ import unicode_literals

这将使您所有的 Python2 str文字变成unicode ,这将是兼容性的重要第一步。

其次,如果你真的需要某种兼容性转换功能,试试这个:

def py23_str(value):
    try:  # Python 2
        return unicode(value, errors='ignore', encoding='utf-8')
    except NameError:  # Python 3
        try:
            return str(value, errors='ignore', encoding='utf-8')
        except TypeError:  # Wasn't a bytes object, no need to decode
            return str(value)

我会说我已经编写了一些与 Python2/3 兼容的库,而且我从来不需要这样做。 到目前为止,我只需要在代码顶部添加from __future__ import unicode_literals并在.decode bytes (或 Python2 中的str )对象时调用.decode (即从'rb'模式中读取文件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM