英文文檔:
class bytes([source[, encoding[, errors]]])
Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray– it has the same non-mutating methods and the same indexing and slicing behavior.
Accordingly, constructor arguments are interpreted as for bytearray()
.
說明:
返回值為一個(gè)新的不可修改字節(jié)數(shù)組耗式,每個(gè)數(shù)字元素都必須在0 - 255范圍內(nèi)擎析,是bytearray函數(shù)的具有相同的行為,差別僅僅是返回的字節(jié)數(shù)組不可修改察绷。
當(dāng)3個(gè)參數(shù)都不傳的時(shí)候臼氨,返回長度為0的字節(jié)數(shù)組
>>> b = bytes()
>>> bb''
>>> len(b)
0
- 當(dāng)source參數(shù)為字符串時(shí)电谣,encoding參數(shù)也必須提供尼酿,函數(shù)將字符串使用str.encode方法轉(zhuǎn)換成字節(jié)數(shù)組
>>> bytes('中文') #需傳入編碼格式
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
bytes('中文')
TypeError: string argument without an encoding
>>> bytes('中文','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
- 當(dāng)source參數(shù)為整數(shù)時(shí),返回這個(gè)整數(shù)所指定長度的空字節(jié)數(shù)組
>>> bytes(2)
b'\x00\x00'
>>> bytes(-2) #整數(shù)需大于0殉挽,用于做數(shù)組長度
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
bytes(-2)
ValueError: negative count
- 當(dāng)source參數(shù)為實(shí)現(xiàn)了buffer接口的object對(duì)象時(shí)攻走,那么將使用只讀方式將字節(jié)讀取到字節(jié)數(shù)組后返回
- 當(dāng)source參數(shù)是一個(gè)可迭代對(duì)象,那么這個(gè)迭代對(duì)象的元素都必須符合0 <= x < 256此再,以便可以初始化到數(shù)組里
>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes([256,2,3])
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
bytes([256,2,3])
ValueError: bytes must be in range(0, 256)
- 返回?cái)?shù)組不可修改
>>> b = bytes(10)
>>> bb'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> b[0]
0
>>> b[1] = 1 #不可修改
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
b[1] = 1
TypeError: 'bytes' object does not support item assignment
>>> b = bytearray(10)
>>> b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> b[1] = 1 #可修改
>>> b
bytearray(b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00')