English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
El método bytes() devuelve un objeto byte inmutable, que se inicializa con el tamaño y los datos dados.
La sintaxis del método bytes() es:
bytes([fuente[, encoding[, errors]]])
El método bytes() devuelve un objeto bytes, que es una secuencia de enteros no fijos (no modificables), con un rango de 0 <= x <256.
Si desea usar la versión variable, utilicebytearray()Method.
bytes() has three optional parameters:
source (optional) -The array used to initialize bytes from the source.
encoding (optional) -The encoding of the string if source is a string.
errors (optional) -The action taken when the encoding conversion fails if source is a string (more information:String encoding)
The source parameter can be used to initialize the byte array in the following ways:
Type | Description |
---|---|
String | To convert a string to bytes using str.encode(), you 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 given size and initialization value.
string = "Python is interesting." # Encoded as “utf-8” of the string arr = bytes(string, 'utf-8) print(arr)
When running this program, the output is:
b'Python is interesting.'
size = 5 arr = bytes(size) print(arr)
When running this program, the output is:
b'\x00\x00\x00\x00\x00'
rList = [1, 2, 3, 4, 5] arr = bytes(rList) print(arr)
When running this program, the output is:
b'\x01\x02\x03\x04\x05'