這是 python3 的異常,python2 中並無該異常
出現此類問題的場景如下:
1. 文件讀取或寫入,是否以 'b’ 二進制方式操作,顯然這種方式為 byte
2. 網絡編程,是否傳輸 二進制 字節
解決思路
str 通過 encode 方法編碼為 byte
encode(self, encoding='utf-8', errors='strict')
或者通過 b'' 方法
byte 通過 decode 方法解碼為 str
decode(self, *args, **kwargs)
示例
s1 = 'abc' print(type(s1)) # <class 'str'> s2 = s1.encode() print(type(s2)) # <class 'bytes'> s3 = s2.decode() print(type(s3)) # <class 'str'> s4 = b'123' print(type(s4)) # <class 'bytes'>
參考資料:
