解決UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range
阿新 • • 發佈:2019-01-26
字串在Python內部的表示是unicode編碼,因此,在做編碼轉換時,通常需要以unicode作為中間編碼,即先將其他編碼的字串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。
Decode的作用是將其他編碼的字串轉換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字串str1轉換成unicode編碼。
Encode的作用是將unicode編碼轉換成其他編碼的字串,如str2.encode('gb2312'),表示將unicode編碼的字串str2轉換成gb2312編碼。
因此,轉碼的時候一定要先搞明白,字串str是什麼編碼,然後decode成unicode,然後再encode成其他編碼
程式碼中字串的預設編碼與程式碼檔案本身的編碼一致。
python在安裝時,預設的編碼是ascii,當程式中出現非ascii編碼時,python的處理常常會報這樣的錯UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),python沒辦法處理非ascii編碼的,此時需要自己設定將python的預設編碼,一般設定為utf8的編碼格式。
解決方法有三中:
1.在命令列修改,僅本會話有效:
1)通過>>>sys.getdefaultencoding()檢視當前編碼(若報錯,先執行>>>import sys >>>reload(sys));
2)通過>>>sys.setdefaultencoding('utf8')設定編碼
2.較繁瑣,最有效
1)在程式檔案中以下三句
import sys
reload(sys)
sys.setdefaultencoding('utf8')
3.修改Python本環境(推薦)
在Python的Lib\site-packages資料夾下新建一個sitecustomize.py檔案,內容為:
#coding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
重啟Python直譯器,發現編碼已被設定為utf8,與方案二同效;這是因為系統在Python啟動的時候,自行呼叫該檔案,設定系統的預設編碼,而不需要每次都手動加上解決程式碼,屬於一勞永逸的解決方法。
----以上內容均摘自網路,如有侵權,告知修改。
引用地址:
1.UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position xxx ordinal - bjkandy http://www.tuicool.com/articles/qiqi2i
2.UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) http://www.cnblogs.com/bluescorpio/p/3594359.html
Decode的作用是將其他編碼的字串轉換成unicode編碼,如str1.decode('gb2312'),表示將gb2312編碼的字串str1轉換成unicode編碼。
Encode的作用是將unicode編碼轉換成其他編碼的字串,如str2.encode('gb2312'),表示將unicode編碼的字串str2轉換成gb2312編碼。
因此,轉碼的時候一定要先搞明白,字串str是什麼編碼,然後decode成unicode,然後再encode成其他編碼
程式碼中字串的預設編碼與程式碼檔案本身的編碼一致。
python在安裝時,預設的編碼是ascii,當程式中出現非ascii編碼時,python的處理常常會報這樣的錯UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128),python沒辦法處理非ascii編碼的,此時需要自己設定將python的預設編碼,一般設定為utf8的編碼格式。
解決方法有三中:
1.在命令列修改,僅本會話有效:
1)通過>>>sys.getdefaultencoding()檢視當前編碼(若報錯,先執行>>>import sys >>>reload(sys));
2)通過>>>sys.setdefaultencoding('utf8')設定編碼
2.較繁瑣,最有效
1)在程式檔案中以下三句
import sys
reload(sys)
sys.setdefaultencoding('utf8')
3.修改Python本環境(推薦)
在Python的Lib\site-packages資料夾下新建一個sitecustomize.py檔案,內容為:
#coding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
重啟Python直譯器,發現編碼已被設定為utf8,與方案二同效;這是因為系統在Python啟動的時候,自行呼叫該檔案,設定系統的預設編碼,而不需要每次都手動加上解決程式碼,屬於一勞永逸的解決方法。
----以上內容均摘自網路,如有侵權,告知修改。
引用地址:
1.UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position xxx ordinal - bjkandy http://www.tuicool.com/articles/qiqi2i
2.UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) http://www.cnblogs.com/bluescorpio/p/3594359.html