bytes
bytes是Python 3中特有的,Python 2 里不區(qū)分bytes和str。
- Python 2中
>>> type(b'xxxxx')
<type 'str'>
>>> type('xxxxx')
<type 'str'>
- Python 3中
>>> type(b'xxxxx')
<class 'bytes'>
>>> type('xxxxx')
<class 'str'>
區(qū)別
bytes是byte的序列,而str是unicode的序列。
str 使用encode方法轉(zhuǎn)化為 bytes
bytes通過decode轉(zhuǎn)化為str
str轉(zhuǎn)換成bytes:
In [9]: str1='人生苦短,我用Python!'
In [10]: type(str1)
Out[10]: str
In [11]: b=str1.encode()
In [12]: b
Out[12]: b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!'
In [13]: type(str1.encode())
Out[13]: bytes
bytes轉(zhuǎn)換成str:
In [22]: b
Out[22]: b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!'
In [23]: type(b)
Out[23]: bytes
In [24]: b.decode()
Out[24]: '人生苦短,我用Python!'
In [25]: type(b.decode())
Out[25]: str
在Python 2中由于不區(qū)分str和bytes所以可以直接通過encode()和decode()方法進(jìn)行編碼解碼。而在Python 3中把兩者給分開了這個在使用中需要注意。實(shí)際應(yīng)用中在互聯(lián)網(wǎng)上是通過二進(jìn)制進(jìn)行傳輸,所以就需要將str轉(zhuǎn)換成bytes進(jìn)行傳輸,而在接收中通過decode()解碼成我們需要的編碼進(jìn)行處理數(shù)據(jù)這樣不管對方是什么編碼而本地是我們使用的編碼這樣就不會亂碼。
bytearray
bytearray和bytes不一樣的地方在于,bytearray是可變的。
In [26]: str1
Out[26]: '人生苦短,我用Python!'
In [28]: b1=bytearray(str1.encode())
In [29]: b1
Out[29]: bytearray(b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!')
In [30]: b1.decode()
Out[30]: '人生苦短,我用Python!'
In [31]: b1[:6]=bytearray('生命'.encode())
In [32]: b1
Out[32]: bytearray(b'\xe7\x94\x9f\xe5\x91\xbd\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe7\x94\xa8Python!')
In [33]: b1.decode()
Out[33]: '生命苦短,我用Python!'
補(bǔ)充
Python2
>>> type('foo')
<type 'str'>
>>> type(u'foo')
<type 'unicode'>
>>> type(b'foo')
<type 'str'>
>>> bytes is str
True
>>> b'foo'[0]
'f'
Python3
>>> type('foo')
<class 'str'>
>>> type(u'foo')
<class 'str'>
>>> type(b'foo')
<class 'bytes'>
>>> bytes is str
False
>>> b'foo'[0]
102