English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales básicos de Python

Control de flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos de Python

Objetos y clases de Python

Fecha y hora de Python

Conocimientos avanzados de Python

Manual de referencia de Python

Uso y ejemplo de bytearray() en Python

Python built-in functions

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.

Parámetros de bytearray()

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:

Different source parameters
TypeDescription
String When converting a string to bytes using str.encode(), you must also provideencoding and optionalerrors
IntegerCreate an array that provides size, and all arrays are initialized to null
ObjectThe 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.

bytearray() return value

The bytearray() method returns a byte array of given size and initial value.

Example1: byte array from string

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.')

Example2: byte array of given integer size

size = 5
arr = bytearray(size)
print(arr)

When running the program, the output is:

bytearray(b'\x00\x00\x00\x00\x00')

Example3: byte array in an iterable list

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')

Python built-in functions