Introduction: Python bytes() Function
When working with Python, there are situations where you need to store or process binary data that should not be modified after it is created. Whether you’re reading binary files, handling encoded text or working with network data, having immutable binary data helps protect the original content from accidental changes.
Without an immutable binary object, binary data could be modified unintentionally, making programs less reliable and increasing the risk of unexpected errors.
A simple and reliable solution to these challenges is the Python bytes() Function.
What it is: The bytes() function is a built-in Python function that creates an immutable sequence of bytes. Unlike a bytearray, the contents of a bytes object cannot be modified after it is created, making it suitable for working with read-only binary data.
Take a look at a simple example to understand how it works.
You can also explore its practical applications across different programming tasks.
Now let’s understand its syntax, parameters, and return value before exploring practical examples.
💡 Tip: The bytes() function is just one of Python’s built-in functions. Explore the complete Python Built-in Functions Learning Guide to discover more useful functions with practical examples.
Syntax, Parameters, Return Value and Examples: Python bytes() Function
The following section explains the syntax, parameters, return value, and a quick example of the Python bytes() Function.
Syntax
bytes()
bytes(source)
bytes(source, encoding)
bytes(source, encoding, errors)
Parameters
| Parameter | Description |
|---|---|
source (optional) |
The data used to create the bytes object. It can be an integer, string, iterable of integers, another bytes-like object, or an object that supports the buffer protocol. |
encoding (optional) |
Specifies the character encoding to use when the source is a string, such as "utf-8".
|
errors (optional) |
Specifies how encoding errors should be handled. Common error-handling options include "strict", "ignore", and "replace".
|
Return Value
| Return Value | Description |
|---|---|
bytes object |
Returns an immutable sequence of bytes. |
Quick Example
The following example creates a bytes object from a string.
data = bytes("Python", "utf-8")
print(data)
# Output:
b'Python'
The string "Python" is encoded using UTF-8, and the resulting byte values are stored in a bytes object. Since bytes objects are immutable, their contents cannot be changed after they are created.
How the Python bytes() function works?
- The
bytes()function creates an immutable sequence of bytes. - It can create an empty bytes object or initialize one using integers, strings, bytes-like objects, or other iterable objects.
- When a string is provided, an encoding must also be specified.
- Unlike a
bytearray, the contents of abytesobject cannot be modified after creation. - It is commonly used when binary data should remain unchanged.
Examples: bytes() Function
The following examples show how the Python bytes() Function works in different programming scenarios.
Example 1: Creating an Empty bytes Object
data = bytes()
print(data)
# Output:
b''
Explanation: Calling bytes() without any arguments creates an empty immutable bytes object.
Example 2: Creating a bytes Object from a String
text = bytes("Python", "utf-8")
print(text)
# Output:
b'Python'
Explanation: Here, the string is encoded using UTF-8 and the resulting byte values are stored in an immutable bytes object.
Example 3: Creating a bytes Object from a List of Integers
numbers = bytes([65, 66, 67, 68])
print(numbers)
# Output:
b'ABCD'
Explanation: Each integer represents an ASCII byte value, so the resulting bytes object contains the byte sequence b'ABCD'.
Example 4: Creating bytes from User Input
text = input("Enter some text: ")
data = bytes(text, "utf-8")
print(data)
# Sample Output:
Enter some text: Hello
b'Hello'
Explanation: After the user enters text, the bytes() function encodes it using UTF-8 and stores the resulting byte values in an immutable bytes object.
Example 5: Accessing Individual Bytes
data = bytes("Python", "utf-8")
print(data[0])
# Output:
80
Explanation: Accessing an index returns the integer value of the corresponding byte. Here, 80 is the ASCII value of P.
Example 6: Attempting to Modify a bytes Object
data = bytes(b"Python")
data[0] = 74
# Output:
TypeError: 'bytes' object does not support item assignment
Explanation: A bytes object cannot be modified after it is created, so assigning a new value to an element raises a TypeError.
Use Cases: When to use the bytes() Function
Below are some common situations where the Python bytes() Function becomes useful:
- Creating immutable binary data.
- Reading and processing binary files.
- Working with network communication and protocols.
- Encoding text before storing or transmitting it.
- Passing binary data to libraries and APIs.
- Preventing accidental modification of byte data.
Key Takeaways: bytes() Function
Before wrapping up, here are the key points to remember about the Python bytes() Function:
- The
bytes()function creates an immutable sequence of bytes. - It accepts integers, strings, bytearrays, iterables of integers, and other supported objects.
- When creating a
bytesobject from a string, an encoding must be specified. - Unlike a
bytearray, abytesobject cannot be modified after creation. - It is commonly used when working with binary files, encoded text, and network communication.
- It provides a reliable way to store binary data that should remain unchanged.
In short, the Python bytes() Function provides a simple and reliable way to create immutable binary data, making it ideal for working with byte sequences that should not be modified.