在Python中比较字符串:字符串X是ASCII,字符串Y是UTF
我遇到了一个比较奇怪的问题:我想用Python比较两个字符串,其中一个字符串X是ASCII格式,另一个字符串Y是UTF或Unicode格式。
现在,当我比较这两个字符串时,出现了以下问题:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
filteredtext = [t for t in s if t.lower() not in stopwords]
我该如何确保这两个字符串是相同的格式呢?
祝好。
1 个回答
6
将所有字符串使用底层编码进行转换,然后进行比较:
print unicode(s1, 'ascii') == unicode(s1, 'utf-8')