代碼實例講解python3的編碼問題
python3的編碼問題。
打開python開發(fā)工具IDLE,新建‘codetest.py'文件,并寫代碼如下:
import sys print (sys.getdefaultencoding())
F5運行程序,打印出系統(tǒng)默認(rèn)編碼方式
將字符串從str格式編碼程bytes格式,修改代碼如下:
import sys print (sys.getdefaultencoding()) s = '你好' print (type(s)) b = s.encode('utf-8') print (type(b)) print (b)
其中b = s.encode('utf-8') 等同于b = s.encode() ,因為系統(tǒng)默認(rèn)編碼方式就是utf-8
F5運行程序,打印出內(nèi)容如下,中文必須用utf-8編碼,因為ascii碼表示不了所有漢字,這里暫時不介紹gbk編碼,現(xiàn)在用得很少了,utf-8使用3個字節(jié)表示一個漢字,ascii使用一個字節(jié)表示一個英文字母或字符。
解碼就是從bytes變回str的過程,修改代碼如下:
import sys print (sys.getdefaultencoding()) s = '你好' print (type(s)) b = s.encode('utf-8') print (type(b)) print (b) se = b.decode('utf-8') print (se) print (type(se))
F5運行程序,打印內(nèi)容如下圖,bytes轉(zhuǎn)回str
utf-8編碼兼容ascii,當(dāng)既有中文又有英文時使用encode('utf-8'),英文還是占一個字節(jié),中國三個字節(jié),另外當(dāng)py文件注釋有中文時,需要在頭部添加
#coding:utf-8
相關(guān)文章
Python的Matplotlib庫圖像復(fù)現(xiàn)學(xué)習(xí)
這篇文章主要給大家介紹了關(guān)于如何利用Matplotlib庫圖像復(fù)現(xiàn),matplotlib模塊提供了很高級和非常友好的使用方式,使用起來也是非常方便的,需要的朋友可以參考下2021-08-08