Python2的字符串有兩種:str 和 unicode;Python3的字符串也有兩種:str 和 bytes。
bytes可以是任何二進制數據,文本/圖片/視頻/音頻等等。
str就是文本。
str與bytes互轉
b = b"example" # bytes object
s = "example" # str object
s2b = bytes(s, encoding = "utf8") # str to bytes
s2b = str.encode(s) # str to bytes
s2b = s.encode("utf8") # str to bytes
b2s = str(b, encoding = "utf8") # bytes to str
b2s = bytes.decode(b) # bytes to str
b2s = b.decode("utf8") # bytes to str
略微詳細的介紹
Python3 嚴格區分文本數據
(str)和二進制數據
(bytes)。文本數據
可以變成二進制數據
,但是二進制數據
不一定是文本數據
。比如圖片,視頻也可以用二進制數據(bytes)表示。
所以python3中bytes和str不能混用。因為bytes不一定能變成str,不同類型之間操作就會拋出TypeError的異常。
str和bytes的轉換關系(注意bytes不一定能decode成str哦)
str.encode('encoding') -> bytes
bytes.decode('encoding') -> str
# encoding可以是 utf-8, gb2312, gbk等等
當bytes是圖片,視頻等非文本的二進制內容時,bytes就不能decode成str了。
In [29]: img = open('str-bytes.jpg', 'rb').read()
In [30]: type(img)
Out[30]: bytes
In [31]: img.decode('utf8')
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-31-c9e28f45be95> in <module>()
----> 1 img.decode('utf8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte