English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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() 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:
Type | Description |
---|---|
String | When using str.encode() to convert a string to bytes, it must also provideEncoding and optionalError |
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 bytes() method returns a bytes object with the given size and initial value.
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.'
size = 5 arr = bytes(size) print(arr)
When running the program, the output is:
b'\x00\x00\x00\x00\x00'
rList = [1, 2, 3, 4, 5] arr = bytes(rList) print(arr)
When running the program, the output is:
b'\x01\x02\x03\x04\x05'