Skip to main content

Python bytes() Function

The bytes() function returns an immutable bytes object.

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

note

The difference between bytes() and bytearray() is that bytes() returns an object that can not be modified, and bytearray() returns an object that can be modified.

Syntax

bytes(source, encoding, errors)

bytes() Parameter

Python bytes() function parameters:

ParameterConditionDescription
xOptionalA 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.
encodingOptionalThe encoding of the string like ascii, utf-8, windows-1250, windows-1252, etc.
errorOptionalSpecifies what to do if the encoding fails (strict, replace, ignore, backslashreplace)
note

Notice that different error parameter has different effects:

  • strict will raise an exception in case of an encoding error
  • replace will replace malformed data with a suitable replacement marker, such as ‘?’ or ‘ufffd’
  • ignore will ignore malformed data and continue without further notice
  • xmlcharrefreplace will replace with the appropriate XML character reference (for encoding only)
  • backslashreplace will replace with backslashed escape sequences (for encoding only)

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!"

# string with encoding 'utf-8'
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'