Python bytes() Function



The Python bytes() function is a built-in function that returns a new "bytes" object, which is an immutable sequence of integers in the range 0 <= x < 256. When this function is called without any arguments, it creates a bytes object of size zero.

The bytes object can be initialized in the following ways −

  • String − We can create a bytes object from a string by encoding it using "str.encode()".

  • Integer − If the source is an integer, an array with null value of specified size will be created.

  • Iterable − Creates an array of size equal to the length of iterable.

  • No source − If no source is specified, an array of size 0 is created.

Syntax

The syntax of the Python bytes() function is as follows −

bytes(source)
or,
bytes(source, encoding)
or,
bytes(source, encoding, errors)

Parameters

The Python bytes() function accepts three optional parameters −

  • source − It represents an object such as a list, string, or tuple.

  • encoding − It indicates the encoding of the passed string.

  • errors − It specifies the required action when encoding fails.

Return Value

The Python bytes() function returns a new bytes object of the specified size.

Examples

Let's understand how bytes() function works with the help of some examples −

Example 1

The following example shows how to use the Python bytes() function. Here we are creating an empty bytes object.

empByte_obj = bytes()
print("It is an example of empty byte object:", empByte_obj)

When we run above program, it produces following result −

It is an example of empty byte object: b''

Example 2

In the code below, we are converting a given string into bytes object. For this operation, we use bytes() function by passing string and encoding as parameter values.

strObj = "Tutorials Point bytes object"
str_bytes_obj = bytes(strObj, 'utf-8')
print("Creating bytes object from string:")
print(str_bytes_obj)

Following is an output of the above code −

Creating bytes object from string:
b'Tutorials Point bytes object'

Example 3

The code below demonstrates how to create a bytes object of the specified size. We are going to pass the size and value as arguments to the bytes() function.

size = 5
value = 1
new_bytesObj = bytes([value]*size)
print("Bytes object of the given size:")
print(new_bytesObj)

Output of the above code is as follows −

Bytes object of the given size:
b'\x01\x01\x01\x01\x01'

Example 4

The following code illustrates how to convert a bytearray into bytes object using the bytes() function. To do so, we simply need to pass the bytearray as a parameter value to the bytes() function.

byteArray = bytearray([84, 85, 84, 79, 82, 73, 65, 76, 83])
bytesObj = bytes(byteArray)
print("The bytes object from byte array:")
print(bytesObj)

Following is an output of the above code −

The bytes object from byte array:
b'TUTORIALS'
python_built_in_functions.htm
Advertisements