1. 程式人生 > 實用技巧 >python3編碼轉換(字串/位元組碼)——Python

python3編碼轉換(字串/位元組碼)——Python

str->bytes:encode編碼
bytes->str:decode解碼

字串通過編碼成為位元組碼,位元組碼通過解碼成為字串。

>>> text = '我是文字'
>>> text
'我是文字'
>>> print(text)
我是文字
>>> bytesText = text.encode()
>>> bytesText
b'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac'
>>> print(bytesText)
b
'\xe6\x88\x91\xe6\x98\xaf\xe6\x96\x87\xe6\x9c\xac' >>> type(text) <class 'str'> >>> type(bytesText) <class 'bytes'> >>> textDecode = bytesText.decode() >>> textDecode '我是文字' >>> print(textDecode) 我是文字

其中decode()與encode()方法可以接受引數,其宣告分別為:

bytes.decode(encoding="
utf-8", errors="strict") str.encode(encoding="utf-8", errors="strict")

其中的encoding是指在解碼編碼過程中使用的編碼(此處指“編碼方案”是名詞),errors是指錯誤的處理方案。