Python bytes()
Function
The bytes() function in Python is used to create an immutable sequence of bytes. It is commonly used when working with binary data, such as reading from or writing to files, networking, or handling encoded data.
Syntax
bytes([source[, encoding[, errors]]])
Parameters:
source
(optional) – Data to convert into bytes (e.g., string, iterable, or integer).encoding
(optional) – Encoding to use when the source is a string.errors
(optional) – Specifies how to handle encoding errors (e.g., 'strict', 'ignore').
Returns:
- A bytes object, which is an immutable sequence of integers in the range 0 <= x < 256.
Example 1: Creating Empty Bytes
empty = bytes()
print(empty)
b''
Example 2: Convert String to Bytes
text = "hello"
b = bytes(text, encoding="utf-8")
print(b)
b'hello'
Example 3: Create Bytes from List of Integers
data = [65, 66, 67]
b = bytes(data)
print(b)
b'ABC'
Example 4: Using Integer as Argument
b = bytes(4)
print(b)
b'\x00\x00\x00\x00'
This creates a bytes object of size 4 with each byte set to 0.
Use Cases
- Working with binary files
- Storing or transmitting encoded data
- Handling network protocols or buffered data
- Required when interacting with low-level APIs
Common Mistakes
- Forgetting to specify
encoding
when converting a string - Providing numbers outside the range 0-255 in a list/iterable
- Expecting the result to be mutable (use
bytearray()
for mutable sequences)
Interview Tip
The bytes()
function is often useful in interviews involving file I/O, sockets, or data serialization. Remember that it's immutable!
Summary
bytes()
creates immutable sequences of bytes- Can be created from strings (with encoding), integers, or iterables
- Immutable – to change values, use
bytearray()
Practice Problem
Ask the user to input a string, convert it to bytes, and print the result.
user_input = input("Enter a message: ")
b = bytes(user_input, encoding="utf-8")
print("Byte version:", b)