說明:
1. 返回值為一個新的不可修改字節數組,每個數字元素都必須在0 - 255范圍內,是bytearray函數的具有相同的行為,差別僅僅是返回的字節數組不可修改。
2. 當3個參數都不傳的時候,返回長度為0的字節數組
>>> b = bytes() >>> b b'' >>> len(b) 0
3. 當source參數為字符串時,encoding參數也必須提供,函數將字符串使用str.encode方法轉換成字節數組
>>> 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'
4. 當source參數為整數時,返回這個整數所指定長度的空字節數組
>>> bytes(2) b'\x00\x00' >>> bytes(-2) #整數需大於0,用於做數組長度 Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> bytes(-2) ValueError: negative count
5. 當source參數為實現了buffer接口的object對象時,那么將使用只讀方式將字節讀取到字節數組后返回
6. 當source參數是一個可迭代對象,那么這個迭代對象的元素都必須符合0 <= x < 256,以便可以初始化到數組里
>>> 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)
7. 返回數組不可修改
>>> b = bytes(10) >>> b b'\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')
內容總結:
字節碼轉換為字符串:
1 s = "中國人,美國人" 2 byte_str = bytes(s,encoding="utf-8") 3 print(byte_str)
輸出結果:
b'\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba,\xe7\xbe\x8e\xe5\x9b\xbd\xe4\xba\xba'
字符串轉換為字節碼:
1 tr_str = str(byte_str,encoding="utf-8") 2 print(tr_str)
輸出結果:
中國人,美國人