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

Tutoriel de base Python

Contrôle de flux Python

Fonctions 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 la méthode bytes() en Python

Python built-in functions

La méthode bytes() retourne un objet byte immutable, initialisé avec la taille et les données données.

La syntaxe de la méthode bytes() est :

bytes([source[, encoding[, errors]]])

la méthode bytes() retourne un objet bytes, qui est une séquence d'entiers non modifiables (ne peut pas être modifié) dans l'intervalle 0 <= x <256。

Pour utiliser la version variable, veuillez utiliserbytearray()Method.

bytes() parameters

bytes() has three optional parameters:

  • source (optional) -The array used to initialize bytes from the source.

  • 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 source parameter can be used to initialize the byte array as follows:

Different source parameters
TypeDescription
StringWhen using str.encode() to convert a string to bytes, it must also provideEncoding and optionalError
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
IterableCreate 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

bytes() return value

The bytes() method returns a bytes object with the given size and initial value.

Example1: Convert the string to bytes

string = "Python is interesting."
# Encoding as “utf-8” string
arr = bytes(string, 'utf-8)
print(arr)

When running the program, the output is:

b'Python is interesting.'

Example2: Create a byte of a given integer size

size = 5
arr = bytes(size)
print(arr)

When running the program, the output is:

b'\x00\x00\x00\x00\x00'

Example3: Convert an iterable list to bytes

rList = [1, 2, 3, 4, 5]
arr = bytes(rList)
print(arr)

When running the program, the output is:

b'\x01\x02\x03\x04\x05'

Python built-in functions