UnicodeDecodeError
表示錯誤發生在解碼的一個字節串到Unicode中。
>>> u"\N{EM DASH}".encode('utf-8').encode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
u"\N{EM DASH}".encode('utf-8')
是一個字節串並調用.encode('utf-8')
的第二次導致了潛在隱性.decode(sys.getdefaultencoding())
:
特別是,如果你試圖編碼字節字符串代替Unicode字符串Python的2可能發生到UnicodeDecodeError
。
IDE做什麼不同,它不會落在這個錯誤?
它可能工作在IDE因爲它改變sys.getdefaultencoding()
到utf-8
你不應做。如您的問題所示,它可能會隱藏錯誤。在一般情況下,它也可能會破壞不希望Python的2
我同時編碼unicode字符串非ASCII sys.getdefaultencoding()
第三方庫,因爲它是測試對像ñ另一個包含字母一根弦的唯一途徑或ç。
您應該use unicodedata.normalize()
instead:
>>> import unicodedata
>>> a, b = u'\xf1', u'n\u0303'
>>> print(a)
ñ
>>> print(b)
ñ
>>> a == unicodedata.normalize('NFC', b)
True
注意:你的問題的代碼可能會產生令人驚訝的結果:
#XXX BROKEN, DON'T DO IT
...address_name.upper() in i[5].upper().encode('utf-8')...
address_name.upper()
電話bytes.upper
方法而i[5].upper()
電話unicode.upper
方法。前者不支持Unicode,它可能取決於當前的語言環境,後者是更好,但執行不區分大小寫的比較,使用.casefold()
方法代替:
key = unicode_address_name.casefold()
... if key == i[5].casefold()...
在一般情況下,如果需要unicode字符串,然後進行排序你可以使用icu.Collator
。比較默認的排序辭書:
>>> L = [u'sandwiches', u'angel delight', u'custard', u'éclairs', u'glühwein']
>>> sorted(L)
[u'angel delight', u'custard', u'gl\xfchwein', u'sandwiches', u'\xe9clairs']
與秩序en_GB
區域:
>>> import icu # PyICU
>>> collator = icu.Collator.createInstance(icu.Locale('en_GB'))
>>> sorted(L, key=collator.getSortKey)
[u'angel delight', u'custard', u'\xe9clairs', u'gl\xfchwein', u'sandwiches']
「直接」?你的意思是從命令提示符?什麼OS?什麼是您的控制檯的編碼? – 2010-10-20 14:53:14
我不知道Eclipse,但是你是什麼意思「這是測試一個字符串與另一個字符串的唯一方法」?在現代Python中,如果你沒有做輸入或輸出(來自文件,數據庫或網絡),即使在這種情況下許多API透明地處理unicode,你也不需要擔心編碼/解碼。什麼是GetValue()方法?哪個庫? – 2010-10-20 14:55:33
Win-1252到UTF-8是一個嚴重的麻煩,我第二個Kelmer關於穩定編碼的問題。 – 2010-10-20 15:09:47