2017-12-27 31 views
0

그래서 두 문자열을 비교하려고합니다. 그 중 하나는 "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을 반환하지만 어쨌든 비교하려고합니다.

예를 들어 유니 코드와 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 : 유니 코드 경고 : 유니 코드 비교 두 인수를 모두 유니 코드로 변환하지 못했습니다 - 불일치로 해석합니다. a [besti-1] == b [bestj-1] : ' –

+0

이상한 ... 전에는 보지 못했습니다. 알고있는 사람을 기다려 봅시다. – Sraw

-1

내가 this post

귀하의 오류 메시지에서 질문에 아주 좋은 답이 있다고 생각하면 유니 코드 개체를 비교하지 않는 것을 나타냅니다. 당신은 아마 지금처럼 STR 객체에 유니 코드 개체를 비교하는 :

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

그래서, 나는 다른 종류의 두 개의 문자열을 비교하는 경우이 https://nedbatchelder.com/text/unipain.html

+0

왜 대답을 복사합니까? 그냥 중복으로 플래그. –