1. 程式人生 > >Python中的encode與decode,詳解字串與位元組物件之間的轉換

Python中的encode與decode,詳解字串與位元組物件之間的轉換

1.相關異常

我們在處理交換的資料時經常遇到這樣的異常:

TypeError: can't use a string pattern on a bytes-like object

TypeError: a bytes-like object is required, not 'str'

...

很顯然,我們要處理的資料是一個位元組物件,即Python中的bytes或bytearray型別,但是我們卻使用了處理字串的方法。

2.相關方法

字串位元組物件之間進行轉換,Python提供了字串的encode()方法和位元組物件的decode()方法。

1) encode(encoding="utf-8", errors="strict")方法
該方法將字串(str)轉換為某種編碼的位元組物件。
  • 引數encoding預設為utf-8(亦即utf_8或utf8),表示預設轉換為utf-8編碼的位元組物件
encoding可以是任何標準編碼,Python中內建的標準編碼表見如下連結:
https://docs.python.org/3/library/codecs.html#standard-encodings
  • errors預設'strict',表示編碼過程中出現錯誤將丟擲UnicodeError
errors還可以是'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace',以及通過 codecs.register_error()註冊的任何值。
2) decode(encoding="utf-8", errors="strict")方法

該方法將位元組物件解碼為原始的字串。

該方法的引數與encode()方法完全一致,此處不再贅述。

在網路傳輸過程中,客戶端要傳送的字串首先要經過encode()編碼轉換為位元組物件,才能在網路中傳輸。在服務端,首先要decode()解碼,將接收到的位元組物件轉換為字串,然後才能進行後續處理。

3. str()中的編解碼

我們通常使用str()將一個物件轉換為字串,事實上這是在呼叫str類的建構函式。

str類的建構函式定義如下:

class str(object=b'', encoding='utf-8', errors='strict')

可見,在使用str()將一個物件轉換為字串時,就是使用了decode()方法的預設引數。

參考連結:

https://docs.python.org/3/library/stdtypes.html#str.encode

https://docs.python.org/3/library/stdtypes.html#bytes.decode

https://docs.python.org/3/library/codecs.html#standard-encodings

https://docs.python.org/3/library/stdtypes.html#str