一、python3對文本和二進制數據做了區分。文本是Unicode編碼,str類型,用於顯示。二進制類型是bytes類型,用於存儲和傳輸。bytes是byte的序列,而str是unicode的序列。
str類型:
1 >>> s = u'你好' 2 >>> s 3 '你好' 4 >>> type(s) 5 <class 'str'>
bytes類型:
1 >>> b = b'abc' 2 >>> b 3 b'abc' 4 >>> type(b) 5 <class 'bytes'>
二、str和bytes之間的轉換關系:str-->encode()-->bytes-->decode()-->str
轉換方式一:encode(),decode()
1 >>> a = u'你好' 2 >>> b = a.encode('utf-8') 3 >>> b 4 b'\xe4\xbd\xa0\xe5\xa5\xbd' 5 >>> type(b) 6 <class 'bytes'> 7 >>> new_a = b.decode('utf-8') 8 >>> new_a 9 '你好' 10 >>> type(new_a) 11 <class 'str'>
轉換方式二:bytes(),str()
1 >>> a = u'你好' 2 >>> b= bytes(a, encoding='utf-8') 3 >>> b 4 b'\xe4\xbd\xa0\xe5\xa5\xbd' 5 >>> type(b) 6 <class 'bytes'> 7 >>> new_a = str(b, encoding='utf-8') 8 >>> new_a 9 '你好' 10 >>> type(new_a) 11 <class 'str'>
三、bytearray類型
bytearray類是range 0 < = x < 256的一個可變序列。
可選的源參數可以用幾種不同的方式來初始化數組:
- 如果它是一個字符串,那么您還必須給出編碼(以及可選的錯誤)參數;bytearray()然后使用str.encode()將字符串轉換為字節。
- 如果它是一個整數,那么數組將具有這個大小,並將用null字節初始化。
- 如果它是符合緩沖區接口的對象,則將使用對象的只讀緩沖區來初始化字節數組。
- 如果它是可迭代的,那么它必須是range 0 < = x < 256的整數的迭代,它被用作數組的初始內容
- 如果沒有參數,則創建一個大小為0的數組。
當源參數是一個字符串時:
1 >>> b = bytearray(u'你好', encoding='utf-8') 2 >>> b 3 bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd') 4 >>> type(b) 5 <class 'bytearray'>
當源參數是一個整數時:
1 >>> b = bytearray(5) 2 >>> b 3 bytearray(b'\x00\x00\x00\x00\x00') 4 >>> type(b) 5 <class 'bytearray'>
當源參數是一個可迭代對象,那么這個迭代對象的元素都必須符合0 <= x < 256:
1 >>> b = bytearray([1, 2, 3, 4, 255]) 2 >>> b 3 bytearray(b'\x01\x02\x03\x04\xff') 4 >>> type(b) 5 <class 'bytearray'
四、bytes和bytearray區別
bytes是不可變的,同str。bytearray是可變的,同list。
1 >>> b = bytearray() 2 >>> b 3 bytearray(b'') 4 >>> b.append(10) 5 >>> b 6 bytearray(b'\n') 7 >>> b.append(100) 8 >>> b 9 bytearray(b'\nd') 10 >>> b.remove(100) 11 >>> b 12 bytearray(b'\n') 13 >>> b.insert(0, 150) 14 >>> b 15 bytearray(b'\x96\n') 16 >>> b.extend([1, 3, 5]) 17 >>> b 18 bytearray(b'\x96\n\x01\x03\x05') 19 >>> b.pop(2) 20 1 21 >>> b 22 bytearray(b'\x96\n\x03\x05') 23 >>> b.reverse() 24 >>> b 25 bytearray(b'\x05\x03\n\x96') 26 >>> b.clear() 27 >>> b 28 bytearray(b'')
五、bytes和 bytearray轉換
1 >>> b = b'abcdef' 2 >>> bay = bytearray(b) 3 >>> bay 4 bytearray(b'abcdef') 5 >>> b = bytes(bay) 6 >>> b 7 b'abcdef'
六、bytearray和str轉換
1 >>> a = 'abcdef' 2 >>> b = bytearray(a, encoding='utf-8') 3 >>> b 4 bytearray(b'abcdef') 5 >>> a = b.decode(encoding='utf-8') 6 >>> a 7 'abcdef'