Python built-in functions (8) -- bytes, pythonbytes
English document:
Classbytes([Source[,Encoding[,Errors])
Return a new "bytes" object, which is an immutable sequence of integers in the range0 <= x < 256.bytesIs an immutable versionbytearray-It has the same non-mutating methods and the same indexing and slicing behavior.
Accordingly, constructor arguments are interpreted asbytearray().
Note:
1. the returned value is a new unmodifiable byte array. Each numeric element must be in the range of 0-255. The same behavior exists in the bytearray function. The difference is that the returned byte array cannot be modified.
2. If none of the three parameters are passed, a byte array with a length of 0 is returned.
>>> b = bytes()>>> bb''>>> len(b)0
3. When the source parameter is a string, the encoding parameter must also be provided. The function converts the string to a byte array using the str. encode method.
>>> Bytes ('Chinese') # The encoding format Traceback (most recent call last) must be input: File "<pyshell #14>", line 1, in <module> bytes ('Chinese') TypeError: string argument without an encoding> bytes ('Chinese', 'utf-8 ') B '\ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87' >>> 'Chinese '. encode ('utf-8') B '\ xe4 \ xb8 \ xad \ xe6 \ x96 \ x87'
4. When the source parameter is an integer, an empty byte array of the length specified by this integer is returned.
>>> Bytes (2) B '\ x00 \ x00' >>> bytes (-2) # The integer must be greater than 0, used for Traceback (most recent call last ): file "<pyshell #19>", line 1, in <module> bytes (-2) ValueError: negative count
5. When the source parameter is an object that implements the buffer Interface, read-only bytes to the byte array and return
6. When the source parameter is an iteratable object, all elements of this iteration object must conform to 0 <= x <256, so that they can be initialized to the array.
>>> 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. The returned array cannot be modified.
>>> B = bytes (10) >>> bb '\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00'> B [0] 0> B [1] = 1 # Traceback (most recent call last) cannot be modified): File "<pyshell #6>", line 1, in <module> B [1] = 1 TypeError: 'bytes 'object does not support item assignment >>> B = bytearray (10) >>> bbytearray (B '\ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00')> B [1] = 1 # modifiable >>> bbytearray (B '\ x00 \ x01 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 \ x00 ')