This article introduces the Python built-in bytes function in detail:
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 ().
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"
", Line 1, in
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"
", Line 1, in
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 "
", line 1, in
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] >> B [1] = 1 # traceback (most recent call last) cannot be modified): File"
", Line 1, in
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 ')
The above is a detailed description of the Python built-in bytes function. For more information, see other related articles in the first PHP community!