Skip to content

Python bytes() Function

How to use Python's bytes() function to create immutable byte objects from strings, integers, or iterables with custom encoding and error handling.

The bytes() function returns an immutable bytes object.

It can convert objects into bytes objects, or create empty bytes object of the specified size.

Syntax

bytes(source, encoding, errors)

bytes() Parameter

Python bytes() function parameters:

Parameter Condition Description
x Optional A source to use when creating the bytearray object.
If it is an integer, an empty bytearray object of the specified size will be created.
If it is a String, make sure you specify the encoding of the source.
encoding Optional The encoding of the string like ascii, utf-8, windows-1250, windows-1252, etc.
error Optional Specifies what to do if the encoding fails (strict, replace, ignore, backslashreplace)

byte() Return Value

Python bytes() method returns a bytes object of the given size and initialization values.

Examples

bytes() function to convert string to bytes

string = "This is Tutorial Reference!"

arr = bytes(string, 'utf-8')
print(arr)

output

b'This is Tutorial Reference!'

bytes() function to create a byte of a given integer size

size = 5

arr = bytes(size)
print(arr)

output

b'\x00\x00\x00\x00\x00'

bytes() function to convert iterable list to bytes

my_list = [1, 2, 3, 4, 5]

arr = bytes(my_list)
print(arr)

output

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