Home >Backend Development >Python Tutorial >Detailed explanation of bytearray usage of python function
bytearray([source [, encoding [, errors]]]) returns a byte array. The Bytearray type is a variable sequence, and the value range of the elements in the sequence is [0,255].
Parameterssource:
If source is an integer, return an initialization array with the length of source;
If source is a string, then follow The specified encoding converts the string into a byte sequence;
If the source is an iterable type, the element must be an integer in [0, 255];
If the source is an interface with the buffer Consistent object, this object can also be used to initialize bytearray.
Version: Newly introduced after python2.6, can also be used in python3!!
Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
New in version 2.6.
>>> a = bytearray(3) >>> a bytearray(b'\x00\x00\x00') >>> a[0] >>> a[1] >>> a[2] >>> b = bytearray("abc") >>> b bytearray(b'abc') >>> b[0] >>> b[1] >>> b[2] >>> c = bytearray([1, 2, 3]) >>> c bytearray(b'\x01\x02\x03') >>> c[0] >>> c[1] >>> c[2] >>> d = bytearray(buffer("abc")) >>> d bytearray(b'abc') >>> d[0] >>> d[1] >>> d[2]
The above is the detailed content of Detailed explanation of bytearray usage of python function. For more information, please follow other related articles on the PHP Chinese website!