日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python3 的 encode 与 decode

發布時間:2024/9/30 python 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python3 的 encode 与 decode 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

編碼那些事:

? ? ? ?亂碼問題一直是開發中比較常見的問題,特別是在 windows 平臺下開發,會經常遇到,其實亂碼產生的原因就是編碼與解碼的方式不一致造成的,在 windows 下默認使用的是 GBK 編碼,而開發時普遍使用的是 utf-8。在 IDE 這類內置控制臺運行的時候,控制臺的默認編碼就是 GBK(即使你通過注冊表修改了控制臺的默認編碼,默認情況下 IDE 的默認編碼仍舊是會是 GBK) ,所以一但出現中文等非 ASCII 輸出,就會出現亂碼。所以有些時候出現你所看到的亂碼并不見得是你的程序內部編碼轉換出現問題。

? ? ? 關于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?數組。從源碼中可以看出其默認的編碼方式就是 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 按照指定參數解碼成 String 對象。

總結

以上是生活随笔為你收集整理的Python3 的 encode 与 decode的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。