我在这个比较函数中遇到了一些尴尬的代码:
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
目标是在进行比较之前确保this
和that
使用相同的编码。但这似乎是一种尴尬的方式。有更简洁的方法吗?
答案 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