2016年5月15日 星期日

[python] unicode decode encode 的秘密

python 2.7
u"abc中文" == unicode 物件
"abc中文" == str 物件

python 3.x
u"abc中文" == unicode 物件
"abc中文" == unicode 物件

所以大多數問題出現在 python 2.7
以下使用 2.7 的觀點來看:

encode == 把 unicode 物件轉為 str 物件
strUTF8 = u"abc中文".encode("utf-8")  == str 物件
strBIG5 = u"abc中文".encode("big5")  == str 物件
strCP950 = u"abc中文".encode("cp950")  == str 物件

decode == 把 str 物件轉為 unicode 物件
strUTF8 .decode("utf-8") == unicode 物件
strBIG5.decode("big5") == unicode 物件
strCP950.decode("cp950") == unicode 物件

秘密:
如果 str 物件 執行 encode 相當於 "先 decode 為 unicode 再 encode", ex:

strBIG5.encode("cp950") == strBIG5.decode("ascii").encode("cp950")

重點在於 decode 過程會使用 python 的預設系統編碼 ascii 而不是使用 big5
造成 明明是呼叫 encode 卻報錯 "無法使用 ascii 進行 decode " 之類的奇怪結果


沒有留言: