python - 如何在没有外部模块的情况下跨 pythons 2 和 3 透明地处理字符串?

标签 python python-2to3

什么是通用字符串处理的最简单方法,它可以在 python2 和 python3 中工作,而无需使用像 six 这样的第三方模块? ?

我可以使用 if sys.version_info > (3, 0)... 但无法想出一种方法来干净地覆盖字符串方法以进行编码/解码和来自字节透明?

目标是找到允许编写独立的版本不可知脚本(没有依赖项)的最少可能代码。

最佳答案

six source code并不太复杂,为什么不将字符串部分复制到您的代码库中呢?这样你就有了一个完善的统一字符串处理方法。 IE。下面的代码应该做的:

import sys

PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3

if PY3:
    text_type = str
    binary_type = bytes
else:
    text_type = unicode
    binary_type = str


def ensure_binary(s, encoding='utf-8', errors='strict'):
    if isinstance(s, text_type):
        return s.encode(encoding, errors)
    elif isinstance(s, binary_type):
        return s
    else:
        raise TypeError("not expecting type '%s'" % type(s))


def ensure_str(s, encoding='utf-8', errors='strict'):
    if not isinstance(s, (text_type, binary_type)):
        raise TypeError("not expecting type '%s'" % type(s))
    if PY2 and isinstance(s, text_type):
        s = s.encode(encoding, errors)
    elif PY3 and isinstance(s, binary_type):
        s = s.decode(encoding, errors)
    return s


def ensure_text(s, encoding='utf-8', errors='strict'):
    if isinstance(s, binary_type):
        return s.decode(encoding, errors)
    elif isinstance(s, text_type):
        return s
    else:
        raise TypeError("not expecting type '%s'" % type(s))

关于python - 如何在没有外部模块的情况下跨 pythons 2 和 3 透明地处理字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293633/

相关文章:

python - 使用 sudo 在 Python 3.6 中导入错误?

python - 在将字符串与字节进行比较时,你能让 Python3 出错吗?

python - Traceback.py 尝试比较 int 和 'limit',这会解析为 ImportError

Python 2 和 Python 3 双重开发

python - 如何在 Windows 中使用 2to3 工具?

python - 如何使用 python 按特定顺序对文件名进行排序

python - tkFileDialog 不将结果转换为 Windows 上的 Python 列表

python - 根据名称作为列表中的字符串调用函数

python - 如何合并字典,从匹配的键中收集值?

python - 有没有办法通过 pip install 运行 2to3?