天天看點

python bytearray轉string_Python中 str、bytes、bytearray的互相轉化

在一次aes解密中,我完全弄混了str、bytes、bytearray,結果導緻解密的結果不正确。在這裡記錄一下三者的差別和互相轉化的方法。

首先str是采用Unicode編碼方式的序列,主要用于顯示。

而bytes是位元組序列,主要用于網絡和檔案傳輸。

bytearray和bytes是一樣的,隻是它是可變的,它們的關系和str與list類似。

在aes解密或者網絡資料中,資料應該是bytes或bytearray。

str和bytes的互相轉化就是編碼和解碼。

str——》bytes (encode)

str="aabbcc"

bytes=str.encode('utf-8')

print(str)

aabbcc

print(bytes)

b'aabbcc'

更簡單的方式是使用b聲明是bytes

bytes=b'aabbcc'

bytes——》str (decode)

bytes=b"aabbcc"

str=bytes.decode('utf-8')

print(bytes)

b'aabbcc'

print(str)

aabbcc

bytes和str轉化為bytearray都依賴于bytearray函數

bytes——》bytearray

bytes=b"aabbcc"

byarray=bytearray(bytes)

print(byarray)

bytearray(b'aabbcc')

str——》bytearray (encoding)

str="aabbcc"

byarray=bytearray(str)

print(byarray)

bytearray(b'aabbcc')

常見的網絡傳輸時,有hex字元串轉為bytearray的需求可以使用bytearray.fromhex(),這時是不需要編碼的。

hexstr="098811"

byarray=bytearray.fromhex(hexstr)

print(byarray)

bytearray(b'\t\x88\x11')

注意到長度減半!!!!!

bytearray轉為str和bytes 依賴于解碼和bytes函數byarray=bytearray("aabbcc",encoding='utf-8')

str=byarray.decode('utf-8')

bytes=bytes(byarray)

print (byarray)

bytearray(b'aabbcc')

print(str)

aabbcc

print(bytes)

b'aabbcc'