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 bytes() en Python

Python built-in functions

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() parameters

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:

Different source parameters
TypeDescription
StringTo convert a string to bytes using str.encode(), you 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 given size and initialization value.

Example1: Convert the string to bytes

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

Example2: Create a byte of a given integer size

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

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

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

Python built-in functions