The bytes() function in Python is a built-in function that returns a new bytes object, which is a fixed-size array of the specified bytes. In Python, a bytes object is represented by the bytes class.
This function is similar to the bytearray() function, but it is immutable, meaning that we cannot modify it after we create it. In other words, once a bytes object is created, we cannot change its value.
The main purpose of the bytes() function is to create an immutable array of bytes object in Python that cannot be modified after creation.
Understanding bytes in Python
In today’s digital world, we often represent and manipulate data as a sequence of bytes. Bytes are one of the most fundamental data types in Python programming language that represents a fixed-size array of bytes, ranging from 0 to 255.
In Python, we use bytes to represent binary data, such as images, audio files, and network packets. Bytes are immutable nature in Python, meaning that once a bytes object is created, we cannot change its value.
Python 3 provides bytes data type a more explicit and efficient way to work with binary data. However, in Python 2, we use str data type to represent both strings and bytes.
Python language offers a built-in function called bytes() that allows us to create and manipulate bytes easily.
Syntax of bytes() Function in Python
Python bytes() function creates an empty bytes object of the specified size. The general syntax of the bytes() function in Python is as:
bytes([source[, encoding[, errors]]])
In the above syntax, the parameters of bytes() function are optional. If we do not specify any parameters, the function returns an empty bytes object. The first parameter “source” can be a string, an object, an iterable of integers, or an integer that defines the size of the bytes object to create.
The bytes() function takes three parameters that are as:
1. source (optional): This is the first parameter that specifies the source of data to create the bytes object.
- If the source parameter is a string, we must encode it with the specified encoding.
- If the parameter source is an integer, it creates an array of provided size, all initialized to null.
- If the parameter source is an object, a read-only buffer of the object will be used to initialize the bytes array.
- If the parameter source is an iterable of integers, it creates an array of size equal to the iterable and initialized to the iterable elements in the range 0 to 256.
2. encoding (optional): This is the second parameter that specifies the encoding of the source if it is a string. The default value is ‘utf-8’.
3. errors (optional): This is the third parameter that specifies an action to take if the encoding conversion fails.
Python bytes() Function Example Programs
Let’s take some coding examples based on the use of bytes() function in Python.
Example 1: Creating an empty bytes object
empty_bytes = bytes()
Example 2: Creating bytes from string
One of the most common use of the bytes() function is to create bytes from the string. We will pass a string as an argument to the bytes() function to create a new bytes object that represents the encoded version of the string. Here’s an example:
# Python program to create bytes object from string. string = "Scientech Easy!" # Convert a string to bytes. bytes_obj = bytes(string, encoding="utf-8") print(bytes_obj)
Output: b'Scientech Easy!'
In this example, we have created a string “Scientech Easy!” and stored it into a variable string. Then, we have converted a string into bytes object using bytes() function. The string “Scientech Easy!” is encoded using the UTF-8 encoding, and the resulting bytes object is displayed. The b prefix before the string tells that it is a bytes object.
Example 3: Creating a byte of given integer size
size = 6 # Creating a bytes object of a given size. bytes_obj = bytes(size) print(bytes_obj)
Example 4: Creating bytes from iterable object
my_list = [80, 121, 116, 104, 111, 110] # Creating bytes object from an iterable object. bytes_obj = bytes(my_list) print(bytes_obj)
In this example, we have created a list object my_list that contains the ASCII values of the characters in the string “Python”. Then, we have passed it as an argument to the bytes() function to create a bytes object.
Converting bytes to other data types
We can convert Bytes to other data types using various methods provided by Python. For example, we can use the decode() function to convert bytes to a string, and to convert bytes to an integer using int.from_bytes() function.
Look at the below example code of converting bytes to a string and an integer.
# Python program to convert bytes to other data types. bytes_obj = b'48' # Converting bytes object to a string. string = bytes_obj.decode() # Converting bytes object to an integer. integer = int.from_bytes(bytes_obj, byteorder='big') print("String representation: ", string) print("Integer representation: ", integer)
Output: String representation: 48 Integer representation: 13368
In this example, we have used the decode() method to convert the bytes object to a string, and the int.from_bytes() method to convert the bytes object to an integer.
How to Modifying bytes in Python?
A bytes object is immutable in Python, meaning that once we create a bytes object, we cannot change or modify its value directly. However, we can create a new bytes object with the desired modifications using slicing or other byte manipulation methods. Here’s an example of modifying a bytes object:
# Python program to modify bytes object. bytes_obj = b'Python is awesome!' # Replace "awesome" with "fun" modified_bytes_obj = bytes_obj[:10] + b'fun' + bytes_obj[17:] print(modified_bytes_obj)
Output: b'Python is fun!'
Best Practices for using bytes() Function in Python
Here are some best practices to keep in mind when using the bytes() function in Python. They are:
1. Use it to convert a string to bytes:
The main use of the bytes() function is to convert a string to bytes. It is especially useful when we work with binary data or when we need to send data over a network.
2. Specify encoding:
While converting a string to bytes object, it is important to specify the encoding parameter if the string contains non-ASCII characters. By default, the bytes() function uses the ‘utf-8’ encoding in Python. However, if your string uses a different encoding, you will have to specify it explicitly.
3. Use it to create byte arrays:
In addition to converting strings to bytes, we can also use the bytes() function to create byte arrays directly. It is useful when we are working with binary data or when we need to manipulate the data in some way.
4. Handle errors appropriately:
While using the bytes() function to convert a string to bytes object, it’s important to handle encoding errors appropriately. By default, the Python bytes() function uses the ‘strict’ error handling mode, which generates a UnicodeError if the string can’t be encoded using the specified encoding. However, we can change this behavior by specifying a different error handling mode using the errors parameter.
5. Use it in combination with other functions:
We can also use the bytes() function in combination with other functions in Python to manipulate binary data. For instance, we can use the struct module to pack and unpack binary data, and then convert the resulting string to bytes using the bytes() function.
In this tutorial, you learned bytes() function in Python with various example programs. Hope that you will have understood the basic concepts of using bytes function.
Thanks for reading!!!