English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode bytearray() retourne un objet bytearray, qui est un tableau de bytes donné.
La syntaxe de la méthode bytearray() est :
bytearray([source[, encoding[, errors]]])
La méthode bytearray() retourne un objet bytearray, qui est une séquence d'entiers modifiables (peut être modifiée), avec une plage de 0 <= x <256.
Si vous souhaitez utiliser une version immuable, veuillez utiliserbytes()méthode.
bytearray() possède trois paramètres optionnels :
source (optional) -The source used to initialize the byte array.
encoding (optional) -If the source is a string, it is the encoding of the string.
errors (optional) -If the source is a string, the action taken when the encoding conversion fails (more information:String encoding)
The bytearray can be initialized using the source parameter in the following ways:
Type | Description |
---|---|
String | When converting a string to bytes using str.encode(), you must also provideencoding and optionalerrors |
Integer | Create an array that provides size, and all arrays are initialized to null |
Object | The read-only buffer of the object will be used to initialize the byte array |
Iterable | Create an array of size equal to the count of the iterable, and initialize it with the elements of the iterable. It must be 0 <= x <256Integer iterable between |
No source (arguments) | Create an array of size 0. |
The bytearray() method returns a byte array of given size and initial value.
string = "Python is interesting." # Encoding as “utf-8” string arr = bytearray(string, 'utf-8') print(arr)
When running this program, the output is:
bytearray(b'Python is interesting.')
size = 5 arr = bytearray(size) print(arr)
When running this program, the output is:
bytearray(b'\x00\x00\x00\x00\x00')
rList = [1, 2, 3, 4, 5] arr = bytearray(rList) print(arr)
When running this program, the output is:
bytearray(b'\x01\x02\x03\x04\x05')