Returns a new byte array.
The ByteArray class is a variable sequence of range 0 < = x < 256.
It has common methods for most mutable sequences, described in variable sequence types, and methods for most byte types, see Byte and ByteArray operations.
The optional source parameter can initialize the array in several different ways:
- If it is a string, then you must also give the encoding (and optionally the error) argument, ByteArray () and then use Str.encode () to convert the string to bytes.
- If it is an integer, the array will have this size and will be initialized with a null byte.
- If it is an object that conforms to the buffer interface, the byte array is initialized with the object's read-only buffer.
- If it is iterative, then it must be an iteration of an integer of range 0 < = x < 256, which is used as the initial content of the array
If there are no parameters, an array of size 0 is created.
Description
1. The return value is a new byte array
2. Returns a byte array with a length of 0 when none of the 3 parameters are passed
1 # !/usr/bin/python 2 3 b = ByteArray ()4print(b) <br>print(len (b))
Results:
1 bytearray (b")2 0
3. The encoding parameter must also be supplied when the source parameter is a string, and the function converts the string to a byte array using the Str.encode method
1 b = ByteArray (' Chinese ')
Results:
1 Traceback (most recent): 2 " d:/py/day001/day1/test.py " in <module>3 b = ByteArray (' Chinese ')4 typeerror:string argument without an encoding
The encoding parameter must also be supplied, and the function converts the string using the Str.encode method to a byte array
1 b = ByteArray (' Chinese 'utf-8')2 Print (b) 3 Print (Len (b))
Results:
1 bytearray (b'\xe4\xb8\xad\xe6\x96\x87')2 6
4. Returns an empty byte array of the length specified by this integer when the source parameter is an integer
1 # !/usr/bin/python3 2 3 B = ByteArray (5)4print(b)5print(len (b))
Execution Result:
1 bytearray (b'\x00\x00\x00\x00\x00')2 5
5. When the source parameter is a type object that implements the buffer interface, a read-only method is used to read the bytes to the byte array and return
1 # !/usr/bin/python3 2 3 B = ByteArray ([1,2,3,4,5])4print(b)5Print (len (b))
Execution Result:
1 bytearray (b'\x01\x02\x03\x04\x05')2 5
6. When the source parameter is an iterative object, the elements of the iteration object must conform to 0 <= x < 256 so that it can be initialized into the array
1 # !/usr/bin/python3 2 3 B = ByteArray ([1,2,3,4,5,256])4print(b)5 Print(len (b))
Execution Result:
1 Traceback (most recent): 2 " d:/py/day001/day1/test.py " in <module>3 b = ByteArray ([1,2,3,4,5,256])4 in Range (0, 256)
Built-in functions in Python (ByteArray)