或許這將使它更加明確:
# -*- coding: utf-8 -*-
words = ['artists', 'Künstler', '藝術家', 'Митець']
for word in words:
print word, type(word), repr(word)
words = [u'artists', u'Künstler', u'藝術家', u'Митець']
for word in words:
print word, type(word), repr(word)
輸出:
artists <type 'str'> 'artists'
Künstler <type 'str'> 'K\xc3\xbcnstler'
藝術家 <type 'str'> '\xe8\x89\xba\xe6\x9c\xaf\xe5\xae\xb6'
Митець <type 'str'> '\xd0\x9c\xd0\xb8\xd1\x82\xd0\xb5\xd1\x86\xd1\x8c'
artists <type 'unicode'> u'artists'
Künstler <type 'unicode'> u'K\xfcnstler'
藝術家 <type 'unicode'> u'\u827a\u672f\u5bb6'
Митець <type 'unicode'> u'\u041c\u0438\u0442\u0435\u0446\u044c'
在你在UTF-8的聲明信源編碼編碼的字節串尚屬首例。他們只能在UTF-8終端上正確顯示。
在第二種情況下,您將獲得Unicode字符串。它們將在任何編碼支持字符的終端上正確顯示。
這裏的字符串是如何顯示437的Windows代碼頁控制檯上,使用Python環境變量來配置Python來替換不支持的字符,而不是提高他們的默認UnicodeEncodeError
例外:
c:\>set PYTHONIOENCODING=cp437:replace
c:\>py -2 x.py
artists <type 'str'> 'artists'
K├╝nstler <type 'str'> 'K\xc3\xbcnstler'
艺术家 <type 'str'> '\xe8\x89\xba\xe6\x9c\xaf\xe5\xae\xb6'
Митець <type 'str'> '\xd0\x9c\xd0\xb8\xd1\x82\xd0\xb5\xd1\x86\xd1\x8c'
artists <type 'unicode'> u'artists'
Künstler <type 'unicode'> u'K\xfcnstler'
??? <type 'unicode'> u'\u827a\u672f\u5bb6'
?????? <type 'unicode'> u'\u041c\u0438\u0442\u0435\u0446\u044c'
字節串大多是垃圾,但Unicode字符串是明智的,因爲該代碼頁不支持中文和俄文。
強制性閱讀:http://bit.ly/unipain – Daenyth