本文實(shí)例講述了Python編碼類型轉(zhuǎn)換方法。分享給大家供大家參考,具體如下:
1:Python和unicode
為了正確處理多語言文本,Python在2.0版后引入了Unicode字符串。
2:python中的print
雖然python內(nèi)部需要將文本編碼轉(zhuǎn)換為unicode編碼來處理,而終端顯示工作則由傳統(tǒng)的Python字符串完成(實(shí)際上,Python的print語句根本無法打印出雙字節(jié)的Unicode編碼字符)。
python的print會對輸出的unicode編碼(對其它非unicode編碼,print會原樣輸出)做自動的編碼轉(zhuǎn)換(輸出到控制臺時(shí)),而文件對象的write方法就不會做,因此,當(dāng)一些字符串用print輸出正常時(shí),write到文件確不一定和print的一樣。
在linux下是按照環(huán)境變量來轉(zhuǎn)換的,在linux下使用locale命令就可以看到。print語句它的實(shí)現(xiàn)是將要輸出的內(nèi)容傳送了操作系統(tǒng),操作系統(tǒng)會根據(jù)系統(tǒng)的編碼對輸入的字節(jié)流進(jìn)行編碼。
1
2
3
4
5
6
7
8
|
>>> str = '學(xué)習(xí)python' >>> str '\xe5\xad\xa6\xe4\xb9\xa0python' #asII編碼 >>> print str 學(xué)習(xí)python >>> str = u '學(xué)習(xí)python' >>> str ####unicode編碼 '\xe5u\xad\xa6\xe4\xb9\xa0python' |
3: python中的decode
將其他字符集轉(zhuǎn)化為unicode編碼(只有中文字符才需要轉(zhuǎn)換)
1
2
3
4
|
>>> str = '學(xué)習(xí)' >>> ustr = str .decode( 'utf-8' ) >>> ustr u '\u5b66\u4e60' |
這樣就對中文字符進(jìn)行了編碼轉(zhuǎn)換,可用python進(jìn)行后續(xù)的處理;(如果不轉(zhuǎn)換的話,python會根據(jù)機(jī)器的環(huán)境變量進(jìn)行默認(rèn)的編碼轉(zhuǎn)換,這樣就可能出現(xiàn)亂碼)
4:python中的encode
將unicode轉(zhuǎn)化為其它字符集
1
2
3
4
5
6
7
8
|
>>> str = '學(xué)習(xí)' >>> ustr = str .decode( 'utf-8' ) >>> ustr u '\u5b66\u4e60' >>> ustr.encode( 'utf-8' ) '\xe5\xad\xa6\xe4\xb9\xa0' >>> print ustr.encode( 'utf-8' ) 學(xué)習(xí) |
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。