将字符串与适用于 Python 2 和 3 的字节进行比较

Compare string to bytes that works in both Python 2 and 3

将字符串对象与在 Python 2 和 Python 3 中工作的字节对象进行比较的最佳方法是什么?假设两者都是 UTF-8。更一般地说,如何编写 Python 2 和 Python 3 两个对象的兼容比较,这两个对象可能都是字符串、字节或 Unicode 对象?

问题是 "asdf" == b"asdf" 在 Python 2 中为真,在 Python 3 中为假。

同时,不能盲目编码或解码对象,因为 Python 2 中的字符串同时具有 encodedecode 方法,但 Python 3 中的字符串只有编码方法。

最后,isinstance(obj, bytes) returns 对于 Python 2 中的任何非 unicode 字符串为真,returns 对于 Python 3 中的仅字节对象为真。

在Python 2 和Python 3 中,任何属于bytes 的实例都有解码方法。因此,您可以执行以下操作:

def compare(a, b, encoding="utf8"):
    if isinstance(a, bytes):
        a = a.decode(encoding)
    if isinstance(b, bytes):
        b = b.decode(encoding)
    return a == b

您可以检查您使用的是 Python 2 还是 3 并采取相应措施:

import sys

if sys.version_info[0] < 3:
    text_type = unicode
else:
    text_type = str

if isinstance(obj, text_type):
    result = obj.encode('utf-8')
else:
    result = obj