The Secret Language of Python Bytes() Function

Etiris Magazine
3 min readFeb 21, 2023

How Python Bytes Speak in a Language Only Machines Understand, and Why You Should Too (If You Want to Talk to Machines and Not People)

One of the many built-in functions in Python is the bytes() function. The bytes() function in Python is a powerful function that is used to create a bytes object from a string or iterable object.

The bytes() function takes an object and an encoding parameter as inputs. The object can be a string, list, tuple, or any other iterable object. The encoding parameter specifies the character encoding that should be used to encode the object into a bytes object.

For example, let’s say we have a string ‘hello world’, and we want to convert it into a bytes object. We can use the bytes() function as follows:

string = 'hello world'
bytes_object = bytes(string, 'utf-8')

In this example, we passed the string ‘hello world’ as the object parameter and ‘utf-8' as the encoding parameter. The utf-8 encoding is one of the most commonly used encodings in Python, and it supports all the characters in the Unicode character set.

The resulting bytes_object is a bytes object that contains the encoded version of the string. We can print the bytes object to see the encoded version of the string.

print(bytes_object)

The output of the above code will be:

b'hello world'

--

--