0

So I want to compare two strings, sometimes one of them will be of type "unicode" and sometimes one of them will be of type "str".

This is what I've currently got:

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

what would be the best solution for this? Right now I am just returning False if the types of the strings are unequal, but I would like to compare them anyways.

I would get an error if I would compare unicode with str for example. /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]

I am using Python 2.7

Sebastian Karlsson
  • 715
  • 1
  • 8
  • 19

1 Answers1

-2
>>> u"a" == "a"
True
>>> "a" == "a"
True
>>> u"a" == u"a"
True

So what is the problem? Or do you mean you want to compare type too?

Sraw
  • 18,892
  • 11
  • 54
  • 87
  • I get a warning in the console if I compare two strings with different types. "Warning: ... Will assume unequal", something like that – Sebastian Karlsson Dec 27 '17 at 07:13
  • `/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]:` – Sebastian Karlsson Dec 27 '17 at 07:14
  • Weird... I haven't seen it before. Let's wait for someone who knows. – Sraw Dec 27 '17 at 07:17