我的代码:
a = '汉'
b = u'汉'
这两个是同一个汉字。但很明显,a == b是False。我该如何解决?请注意,我无法转换a为,utf-8因为我无权访问代码。我需要转换b为正在使用的编码a。
所以,我的问题是,我该怎么做才能将编码b转换为的编码a?
如果您不知道a的编码,则需要:
a的编码b使用检测到的编码进行编码首先,要检测a' 的编码,让我们使用chardet。
$ pip install chardet
现在让我们使用它:
>>> import chardet
>>> a = '汉'
>>> chardet.detect(a)
{'confidence': 0.505, 'encoding': 'utf-8'}
因此,要实际完成您的要求:
>>> encoding = chardet.detect(a)['encoding']
>>> b = u'汉'
>>> b_encoded = b.encode(encoding)
>>> a == b_encoded
True
a使用以下代码解码编码字符串str.decode:
>>> a = '汉'
>>> b = u'汉'
>>> a.decode('utf-8') == b
True
注意utf-8根据源代码编码替换。
两者a.decode都b.encode可以:
In [133]: a.decode('utf') == b
Out[133]: True
In [134]: b.encode('utf') == a
Out[134]: True
请注意str.encode和unicode.decode也可用,不要混淆它们。请参阅编码/解码之间有什么区别?