當python中間處理非ascii編碼時,經常會出現如下錯誤:
unicodedecodeerror: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128)
0x??是超出128的數字,python在預設的情況下認為語言的編碼是ascii編碼,所以無法處理其他編碼,需要設定python的預設編碼為所需要的編碼。
乙個解決的方案是在**中新增:
import
sysreload(sys)
sys.setdefaultencoding(
'gb2312')
另乙個方案是在python的lib/site-packages資料夾下新建乙個sitecustomize.py
檔案(sitecustomize.pyis a special script; python will try to import it on startup, so any code in it will be run automatically.),輸入:
import
syssys.setdefaultencoding(
'gb2312')
這樣就能夠自動的設定編碼了。
ps:1. utf8的編碼是:utf-8
*在日本系統中,可以通過設定成utf-8或者 cp932實現對日文文字,中文文字的正常顯示。
2. 測試已經成功的方法:
>>> import sys
>>> sys.getdefaultencoding()
Python 編碼轉換
coding utf 8 s abc print type s str utf 8 print len s 3 s unicode s str unicode,其中str的每個字元值必須小於128 print type s unicode print len s 3 s u abc print ty...
python編碼轉換
參見 主要介紹了python的編碼機制,unicode,utf 8,utf 16,gbk,gb2312,iso 8859 1 等編碼之間的轉換。常見的編碼轉換分為以下幾種情況 1.自動識別字串編碼 coding utf8 import urllib import chardet rawdata ur...
python 編碼轉換
主要介紹了python的編碼機制,unicode,utf 8,utf 16,gbk,gb2312,iso 8859 1 等編碼之間的轉換。常見的編碼轉換分為以下幾種情況 可以使用 chardet 模組自動識別 字元創編碼 chardet 使用方法 例如 a為unicode編碼 要轉為gb2312。a...