The bytes()
function in Python converts an object to an immutable byte object initialized with a given size and given data.
The bytes()
function can be declared as shown in the code snippet below:
bytes(src, enc, error)
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 src
is a string and enc
is not passed as a parameter, then the bytes()
function returns TypeError
.
The bytes()
function converts an object to an immutable byte object and returns it.
The code below demonstrates the use of the bytes()
function:
str = "Hello world!"toBytes = bytes(str, 'utf-8')print(toBytes)
A string str
is declared in line 1. The bytes()
method is used in line 2 to convert str
to bytes.