这个问题在这里已有答案:
所以我想比较两个字符串,有时其中一个将是“unicode”类型,有时其中一个将是“str”类型。
这就是我目前得到的:
def poll_change(self):
''' Returns a tuple (has_changed, new_element_str) '''
new_element = self.find_element()
old_element = self.read_element_str()
# TODO: handle compare correctly
if type(new_element) is not type(old_element):
changed = False
else:
changed = new_element != old_element
return changed, new_element
什么是最好的解决方案?现在我只是返回False
,如果字符串的类型不相等,但我想比较它们。
如果我将unicode与str进行比较,我会得到一个错误。 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/difflib.py:433: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
a[besti-1] == b[bestj-1]
我正在使用Python 2.7
>>> u"a" == "a"
True
>>> "a" == "a"
True
>>> u"a" == u"a"
True
那么问题是什么?或者你的意思是你想要比较类型?