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

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Knowledge of Python

Python Reference Manual

Python bytes() Usage and Example

Python built-in functions

The bytes() method returns an immutable byte object, which is initialized with the given size and data.

The syntax of the bytes() method is:

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

The bytes() method returns a bytes object, which is an immutable (cannot be modified) sequence of integers, ranging from 0 <= x <256.

If you want to use the variable version, please usebytearray()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 as follows:

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 <256The integer between them is iterable
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 a 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 with 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