What is the bytes() function in Python?
The bytes() function in Python converts an object to an immutable byte object initialized with a given size and given data.
Syntax
The bytes() function can be declared as shown in the code snippet below:
bytes(src, enc, error)
Parameters
-
src: The source object which has to be converted. -
enc: The encoding of the string. -
error: Specifies the way to handle any error. -
All parameters of the
bytes()function are optional. -
If
srcis a string andencis not passed as a parameter, then thebytes()function returnsTypeError.
Return value
The bytes() function converts an object to an immutable byte object and returns it.
Code
The code below demonstrates the use of the bytes() function:
str = "Hello world!"toBytes = bytes(str, 'utf-8')print(toBytes)
Explanation
A string str is declared in line 1. The bytes() method is used in line 2 to convert str to bytes.