python编码,打印不出ou

2024-04-26 05:30:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这两条线在印刷时看起来一模一样,但在引擎盖下并不相等。我需要通过这个键选择一个字典项,但是我得到keyError,因为它们显然不匹配。我试过使用str.encode(“utf-8”)str.decode(“utf-8”)unicode(str,“utf-8”)repr()。什么都没用。我怎样才能使它们像打印时一样相等呢?谢谢

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

Tags: 字典unicodeextrautfencodearprintdecode
1条回答
网友
1楼 · 发布于 2024-04-26 05:30:45

您可以尝试使用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.

相关问题 更多 >