【问题标题】:Equivalent to unicode() function that works with both Python 2.7 and 3.x?相当于适用于 Python 2.7 和 3.x 的 unicode() 函数?
【发布时间】:2017-05-25 15:04:07
【问题描述】:

我正在尝试修改一些旧代码以使其可用于 Python 2 和 3。我正在使用 six package 来完成此任务。

如果我在 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

当然,我可以将py2/3 checkssix.PY2six.PY3 一起使用来运行两个版本之一,但有更好的方法吗?

【问题讨论】:

  • 您可以在 Python 3.3+ 中使用u'string' 语法。
  • 我认为一般来说很难回答这个问题......原则上,你会在 python2.x 中使用unicode 将某些东西(可能是str)强制转换为unicode。在 python3.x 上,类比会将 bytes 强制转换为 str -- 为此,您通常只需 .decode 我认为的字节......

标签: python python-2.7 python-3.x unicode


【解决方案1】:

要回答问题的第二部分,您可以将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 并在创建bytes(或Python2 中的str)对象时调用.decode(即在'rb' 模式下从文件中读取)就是我所需要的远的。

【讨论】:

  • 我明白你在说什么,但我无法控制价值是多少。假设value = 'xyz'。在 2.7 中,unicode(value, errors='ignore', encoding='utf-8') 可以正常工作,但在 3.x 中,与 str(value, errors='ignore', encoding='utf-8') 相同的操作将产生 TypeError: decoding str is not supported
  • 你试过from __future__ import unicode_literals吗?这可能会有所帮助,因此您无需执行此显式解码。
猜你喜欢
  • 2016-04-26
  • 2018-01-07
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 2016-05-04
  • 2013-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多