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

Tutoriel de base Python

Contrôle de flux Python

Fonction en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemple de bytearray() en Python

Python built-in functions

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.

Paramètres de bytearray()

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:

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 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 this 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 this 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 this program, the output is:

bytearray(b'\x01\x02\x03\x04\x05')

Python built-in functions