python中bytes與bytearray以及encode與decode


一、encode與decode

1、bytes主要是給在計算機看的,string主要是給人看的

2、中間有個橋梁就是編碼規則,現在大趨勢是utf8

3、bytes對象是二進制,很容易轉換成16進制,例如\x64

4、string就是我們看到的內容,例如'abc'

5、string經過編碼encode,轉化成二進制對象,給計算機識別

6、bytes經過反編碼decode,轉化成string,讓我們看,但是注意反編碼的編碼規則是有范圍,\xc8就不是utf8識別的范圍

例如encode使用:

"哈哈哈".encode("utf-8")    //執行結果為:b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
"哈哈哈".encode("gbk")   //執行結果為b'\xb9\xfe\xb9\xfe\xb9\xfe'

例如decode使用:

b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'.decode("utf-8")   //執行結果為:'哈哈哈'
b'\xb9\xfe\xb9\xfe\xb9\xfe'.decode("gbk")     //執行結果為:'哈哈哈'
>>> "哈哈哈".encode("utf-8")
b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
>>> "哈哈哈".encode("gbk")
b'\xb9\xfe\xb9\xfe\xb9\xfe'
>>> b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'.decode("utf-8")
'哈哈哈'
>>> b'\xb9\xfe\xb9\xfe\xb9\xfe'.decode("gbk")
'哈哈哈'

二、bytes 與 bytearray

bytes 函數返回一個新的 bytes 對象,該對象是一個 0 <= x < 256 區間內的整數不可變序列。它是 bytearray 的不可變版本。

#將數字轉換為字節對象
bytes(1)     //轉換后的值為:b'\x00'
#獲取12個0填充的byte字節對象
bytes(12)       //值為:b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
#將數字數組轉換為字節對象
bytes([1,2,3])   //值為:b'\x01\x02\x03'
#將字符串轉換為字節對象
bytes("哈哈哈","utf-8")   //值為:b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
#將字符串轉換為字節對象
bytes("哈哈哈","utf-8")  //值為:b'\xb9\xfe\xb9\xfe\xb9\xfe'
>>> bytes(1)
b'\x00'
>>> bytes(12)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes("哈哈哈","utf-8")
b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
>>> bytes("哈哈哈","gbk")
b'\xb9\xfe\xb9\xfe\xb9\xfe'

bytearray() 方法返回一個新字節數組。這個數組里的元素是可變的,並且每個元素的值范圍: 0 <= x < 256。

#將數字轉換為字節數組對象
bytearray(1)     //轉換后的值為:bytearray(b'\x00')
#獲取12個0填充的byte字節數組對象
bytearray(12)       //值為:bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
#將數字數組轉換為字節數組對象
bytearray([1,2,3]   //值為:bytearray(b'\x01\x02\x03')
#將字符串轉換為字節數組對象
bytearray("哈哈哈","utf-8")   //值為:bytearray(b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88')
#將字符串轉換為字節數組對象
bytearray("哈哈哈","gbk")  //值為:bytearray(b'\xb9\xfe\xb9\xfe\xb9\xfe')
>>> bytearray(1)
bytearray(b'\x00')
>>> bytearray(12)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> bytearray([1,2,3])
bytearray(b'\x01\x02\x03')
>>> bytearray("哈哈哈","utf-8")
bytearray(b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88')
>>> bytearray("哈哈哈","gbk")
bytearray(b'\xb9\xfe\xb9\xfe\xb9\xfe')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM