在python中从未知类型转换为UTF-8?

时间:2014-01-12 03:22:49

标签: python unicode

我在这个比较函数中遇到了一些尴尬的代码:

def compare(this, that, encoding="utf-8"):

      if type(this) == type(str()):
           this = this.encode(encoding)
      if type(this) == type(bytes()):
           this = this.decode().encode(encoding)

      if type(that) == type(str()):
           that = that.encode(encoding)
      if type(that) == type(bytes()):
           that = that.decode().encode(encoding)

      # there has to be a faster way...

      return this==that

目标是在进行比较之前确保thisthat使用相同的编码。但这似乎是一种尴尬的方式。有更简洁的方法吗?

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是将两个输入转换为str并进行比较。

def compare(this, that, encoding="utf-8"):
    // convert this to str
    if isinstance(this, bytes):
        this = str(this, encoding)
    // convert that to str
    if isinstance(that, bytes):
        that = str(that, encoding)
    return this == that