Python unicode等于比较失败
这个问题链接到在Python中searchUnicode字符
我使用python编解码器读取unicode文本文件
codecs.open('story.txt', 'rb', 'utf-8-sig') 并试图在其中searchstring。 但是我收到以下警告。
 UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal 
有没有什么特别的方法比较Unicodestring?
 您可以使用==运算符来比较unicode对象是否相等。 
 >>> s1 = u'Hello' >>> s2 = unicode("Hello") >>> type(s1), type(s2) (<type 'unicode'>, <type 'unicode'>) >>> s1==s2 True >>> >>> s3='Hello'.decode('utf-8') >>> type(s3) <type 'unicode'> >>> s1==s3 True >>> 
 但是,您的错误消息表明您没有比较unicode对象。 你可能将一个unicode对象与一个str对象比较,如下所示: 
 >>> u'Hello' == 'Hello' True >>> u'Hello' == '\x81\x01' __main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal False 
看看我是如何试图比较一个unicode对象不符合有效的UTF8编码的string。
我想,你的程序正在比较unicode对象和str对象,而str对象的内容不是有效的UTF8编码。 这似乎可能是你(程序员)不知道哪个variables成立的原因,哪个variables包含UTF8,哪个variables包含从文件读入的字节。
我build议http://nedbatchelder.com/text/unipain.html ,特别是build议创build一个“Unicode三明治”。