我该怎么解决这个问题警告:独角兽警报:Unicode相等比较失败

2024-06-01 00:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

伙计们,当我运行代码时,我收到了两次警告:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal位于if result2=b and c == 'Pass':

因为我三次使用if result2=b and c == 'Pass':三次,只有最后两次有警告。我在网上找不到解决方案,但它们不适合我的代码。这是我的密码,请帮我。Thx先进!在

def XXX1():
    XXXXXX
    if result2==b and c == 'Failed':       ----------no warning
    XXXXXX

def XXX2():
    XXXXXX
    if result2==b and c == 'Failed':       ----------warning
    XXXXXX

def XXX3():
    XXXXXX
    if result2==b and c == 'Pass':         ----------warning
    XXXXXX

一些参数可能有助于:

^{pr2}$

Tags: andto代码警告ifdefunicodepass
1条回答
网友
1楼 · 发布于 2024-06-01 00:18:00

您正在混合Unicode字符串和bytestrings。在进行比较时,Python 2将尝试解码bytestring(ASCII),如果失败,您将得到一个警告:

>>> u'å', u'å'.encode('utf8')
(u'\xe5', '\xc3\xa5')
>>> 'å' == u'å'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

不要混合使用Unicode字符串和bytestrings。尽早解码文本数据,只比较Unicode对象。在上面的例子中,bytestring是UTF-8编码的,因此首先解码为UTF-8可以解决警告。在

对于您的示例代码,beauthoulsoup(正确地)生成Unicode文本。您必须解码CSV数据,请参阅Read and Write CSV files including unicode with Python 2.7以获得解决方案,或者使用str.decode()调用手动解码这两个字符串。在

相关问题 更多 >