【发布时间】: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 checks 与six.PY2 或six.PY3 一起使用来运行两个版本之一,但有更好的方法吗?
【问题讨论】:
-
您可以在 Python 3.3+ 中使用
u'string'语法。 -
我认为一般来说很难回答这个问题......原则上,你会在 python2.x 中使用
unicode将某些东西(可能是str)强制转换为unicode。在 python3.x 上,类比会将 bytes 强制转换为str-- 为此,您通常只需.decode我认为的字节......
标签: python python-2.7 python-3.x unicode