2017-12-27 26 views
0

2つの文字列を比較したい場合がありますが、そのうちの1つが "unicode"型で、時には "str"型の文字列があります。Pythonの2つの文字列を安全に比較する

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

答えて

-1
>>> u"a" == "a" 
True 
>>> "a" == "a" 
True 
>>> u"a" == u"a" 
True 

だから、問題は何ですか?それとも、タイプを比較したいのですか?

+0

をお読みください。 "警告:...等しくないと思われる"など、 –

+0

'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/difflib.py:433:UnicodeWarning:Unicode比較両方の引数をUnicodeに変換するのに失敗しました - それらを不等であると解釈しませんでした a [besti-1] == b [bestj-1]: ' –

+0

奇妙な...以前は見たことがありません。知っている人を待ってみましょう。 – Sraw

-1

私はthis post

あなたのエラーメッセージにあなたの質問に非常に良い答えがあると思いますが、あなたがユニコードオブジェクトを比較していないことを示しています。あなたは、おそらくそうのように、strのオブジェクトにUnicodeオブジェクトを比較している:

>>> 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 

だから、私は別のタイプの2つの文字列を比較する場合、私は、コンソールに警告を取得し、このhttps://nedbatchelder.com/text/unipain.html

+0

なぜ答えをコピーするのですか?重複としてフラグを立てるだけです。 –

関連する問題