Python3 的 encode 与 decode
編碼那些事:
? ? ? ?亂碼問題一直是開發(fā)中比較常見的問題,特別是在 windows 平臺下開發(fā),會經(jīng)常遇到,其實亂碼產(chǎn)生的原因就是編碼與解碼的方式不一致造成的,在 windows 下默認使用的是 GBK 編碼,而開發(fā)時普遍使用的是 utf-8。在 IDE 這類內(nèi)置控制臺運行的時候,控制臺的默認編碼就是 GBK(即使你通過注冊表修改了控制臺的默認編碼,默認情況下 IDE 的默認編碼仍舊是會是 GBK) ,所以一但出現(xiàn)中文等非 ASCII 輸出,就會出現(xiàn)亂碼。所以有些時候出現(xiàn)你所看到的亂碼并不見得是你的程序內(nèi)部編碼轉(zhuǎn)換出現(xiàn)問題。
? ? ? 關于windows 下的亂碼分析和如何修改控制臺的編碼 (l臨時/注冊表永久) ,請參考我的這篇文檔:
? ? ? ?https://blog.csdn.net/gulang03/article/details/81771343
? ? ? 關于常見的幾種編碼簡單介紹參看:
? ? ? ?https://blog.csdn.net/gulang03/article/details/79328868
Python3 中 編碼(encode) 與 解碼 ( decode ) :
? ? ? str.encode():
? ? ? ? ?源碼:? ? ?
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__"""S.encode(encoding='utf-8', errors='strict') -> bytesEncode S using the codec registered for encoding. Default encodingis 'utf-8'. errors may be given to set a different errorhandling scheme. Default is 'strict' meaning that encoding errors raisea UnicodeEncodeError. Other possible values are 'ignore', 'replace' and'xmlcharrefreplace' as well as any other name registered withcodecs.register_error that can handle UnicodeEncodeErrors."""return b""? ? ? ? 從源碼相比可以清楚的看到,其返回值是二進制(binary)的 bytes。所以顧名思義 encode 的作用就是將 str 采用指定的編碼方式解碼,并返回編碼后的 byte?數(shù)組。從源碼中可以看出其默認的編碼方式就是 UTF-8 。也就是 Python3 默認的編碼方式。Python2 之前并不是如此。
? ? ? ?bytes.decode():
? ? ? 源碼:
def decode(self, *args, **kwargs): # real signature unknown"""Decode the bytes using the codec registered for encoding.encodingThe encoding with which to decode the bytes.errorsThe error handling scheme to use for the handling of decoding errors.The default is 'strict' meaning that decoding errors raise aUnicodeDecodeError. Other possible values are 'ignore' and 'replace'as well as any other name registered with codecs.register_error thatcan handle UnicodeDecodeErrors."""pass? ? ? ? decode 顧名思義就是解碼嘍,就是將 bytes 按照指定參數(shù)解碼成 String 對象。
總結
以上是生活随笔為你收集整理的Python3 的 encode 与 decode的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux服务器之间传输文件的四种方式
- 下一篇: Window10/Linux 下安装 s