python - encoding, print 想不通

python - encoding, print can't figure out

这两个字符串在打印时看起来相同,但实际上它们并不相等。我需要通过这个键 select 一个字典项,但我得到 keyError 因为显然它们不匹配。我试过使用 str.encode("utf-8"), str.decode("utf-8"), unicode(str, "utf-8"), repr()。没有任何帮助。我怎样才能使它们像 printed 时一样相等?谢谢

>>> str1 = u"extra\u00f1ar"
>>> str2 = u"extrañar"
>>> str1
u'extra\xf1ar'
>>> str2
u'extran\u0303ar'
>>> print str1
extrañar
>>> print str2
extrañar
>>> str1 == str2
False

您可以尝试使用 unicodedata.normalize,但不能保证有效:

>>> str1 = u'extra\xf1ar'
>>> str2 = u'extran\u0303ar'
>>> str1 == str2
False
>>> print str1; print str2
extrañar
extrañar

所以,观察:

>>> import unicodedata
>>> unicodedata.normalize('NFC', str1)
u'extra\xf1ar'
>>> unicodedata.normalize('NFC', str2)
u'extra\xf1ar'
>>> unicodedata.normalize('NFC', str2) == unicodedata.normalize('NFC', str2)
True
>>> print unicodedata.normalize('NFC', str2); print unicodedata.normalize('NFC', str2)
extrañar
extrañar

一个caveat:

Even if two unicode strings are normalized and look the same to a human reader, if one has combining characters and the other doesn’t, they may not compare equal.