首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使基于`unicode`的逻辑兼容python2-3

如何使基于`unicode`的逻辑兼容python2-3
EN

Stack Overflow用户
提问于 2017-03-09 01:11:41
回答 1查看 264关注 0票数 1

我想让这段代码与python2-3兼容:

代码语言:javascript
复制
def normalize_text(text, ignore_characters=''):
    if type(ignore_characters) not in [list, str, unicode]:
        ignore_characters = ''
    if type(ignore_characters) == str:
        ignore_characters = ignore_characters.decode('utf-8')
    if type(ignore_characters) == list:
        new_ignore_characters = []
        for item in ignore_characters:
            if type(item) == str:
                new_ignore_characters.append(item.decode('utf-8'))
            elif type(item) == unicode:
                new_ignore_characters.append(item)
        ignore_characters = new_ignore_characters

    if type(text) == str:
        text = text.decode('utf-8')

在Python3中的str类型上没有unicodedecode。什么是使这段代码与python2-3兼容的最佳解决方案?

EN

回答 1

Stack Overflow用户

发布于 2017-03-09 01:20:18

我强烈推荐使用库来编写与Python2/3兼容的代码。

另外,用isinstance()代替type()来检查类型。在多重继承的情况下,type()将不起作用:

代码语言:javascript
复制
from six import text_type, binary_type

if isinstance(ignore_characters, binary_type):
   # do something with bytes
elif isinstance(ignore_characters, text_type):
   # do something with unicode.

代码语言:javascript
复制
# Python 2 
>>> import six
>>> six.binary_type, six.text_type
(<type 'str'>, <type 'unicode'>)

# Python 3
>>> import six
>>> six.binary_type, six.text_type
(<class 'bytes'>, <class 'str'>)

另一种方法是根据使用sys.version_info获得的Python版本编写自己的别名,以获得兼容性

库中的compat.py文件就是一个很好的例子:

代码语言:javascript
复制
_ver = sys.version_info

#: Python 2.x?
is_py2 = (_ver[0] == 2)

#: Python 3.x?
is_py3 = (_ver[0] == 3)

if is_py2:
    builtin_str = str
    bytes = str
    str = unicode
    basestring = basestring
    numeric_types = (int, long, float)
    integer_types = (int, long)

elif is_py3:
    builtin_str = str
    str = str
    bytes = bytes
    basestring = (str, bytes)
    numeric_types = (int, float)
    integer_types = (int,)

现在,您可以从此文件导入这些函数,而不是直接使用内置函数。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42677618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档