English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
El método bytearray() devuelve un objeto bytearray que es un array de bytes dados.
La sintaxis del método bytearray() es:
bytearray([fuente[, encoding[, errors]]])
El método bytearray() devuelve un objeto bytearray, que es una secuencia de enteros mutables (pueden modificarse), en el rango 0 <= x <256.
Si desea usar la versión inmutable, utilicebytes()método.
bytearray() tiene tres parámetros opcionales:
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 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 the program, the output is:
bytearray(b'Python is interesting.')
size = 5 arr = bytearray(size) print(arr)
When running the program, the output is:
bytearray(b'\x00\x00\x00\x00\x00')
rList = [1, 2, 3, 4, 5] arr = bytearray(rList) print(arr)
When running the program, the output is:
bytearray(b'\x01\x02\x03\x04\x05')