- __init__() function
- Aliases
- and operator
- argparse
- Arrays
- Booleans
- Bytes
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Context manager
- Data class
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Filter()
- Flask framework
- Floats
- Floor division
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- NumPy library
- OOP
- or operator
- Pandas library
- Parameters
- pathlib module
- Pickle
- print() function
- Property()
- Random module
- range() function
- Raw strings
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- Virtual environment
- While loops
- Zip function
PYTHON
Python Bytes: Syntax, Usage, and Examples
The bytes
type in Python represents a sequence of immutable byte values ranging from 0 to 255. This type is essential when you're working with binary data, such as reading or writing files in binary mode, processing network packets, or handling low-level protocols.
Understanding how Python bytes work, how to convert between strings and bytes, and how to manipulate byte arrays helps you handle many real-world applications—from encoding APIs to image processing and cryptography.
What Are Python Bytes?
Python bytes are sequences of raw 8-bit values. You use them when dealing with non-text data or when you want to encode text in a specific binary format, such as UTF-8 or ASCII.
print(type(b)) # <class 'bytes'>
A bytes object is defined by prefixing a string literal with a b
. You can also use the bytes()
constructor to create a bytes object from a string or an iterable of integers.
Creating Bytes in Python
You can create bytes objects using several approaches:
1. From a String
b = bytes("hello", encoding="utf-8")
2. From a List of Integers
b = bytes([104, 101, 108, 108, 111])
3. Using a Byte Literal
b = b"hello"
These methods let you control how text or numbers are encoded into a compact and binary-safe format.
Convert String to Bytes Python
One of the most common operations is converting a string to a bytes object:
text = "example"
bytes_obj = text.encode("utf-8")
This process is essential when sending data over a network or storing data in binary files. The opposite of this operation—bytes to string—requires decoding.
Python Bytes to String Conversion
To convert bytes back to a string:
bytes_obj = b"example"
text = bytes_obj.decode("utf-8")
Always match the encoding method during decoding to avoid errors.
Working with Byte Arrays in Python
If you need a mutable version of bytes, Python provides the bytearray
type. This lets you modify the binary content directly:
b_arr = bytearray(b"data")
b_arr[0] = 68 # Changes 'd' to 'D'
print(b_arr) # bytearray(b'Data')
Use bytearray
when performance matters and you need to update contents frequently.
Python Can't Concat str to Bytes Error
Trying to concatenate a string and a bytes object will raise an error:
b = b"data"
s = "log"
result = b + s # TypeError: can't concat str to bytes
You must explicitly encode or decode one of them first:
result = b + s.encode("utf-8")
This error message is one of the most common hurdles when combining different types in data serialization tasks.
Use Cases of Python Bytes
1. File I/O in Binary Mode
with open("image.jpg", "rb") as f:
data = f.read()
This reads the binary content of a file into a bytes object.
2. Network Programming
Bytes are required when working with sockets:
import socket
sock = socket.socket()
sock.send(b"GET / HTTP/1.1\r\n\r\n")
3. Encoding/Decoding Data for APIs
JSON APIs often require data to be encoded as UTF-8 bytes before transmission.
Python Convert Bytes to String
You often need to convert binary data into human-readable text. Use .decode()
for this:
b = b"text"
s = b.decode("utf-8")
This is common when reading from a network buffer or file input.
Python Convert String to Bytes
For converting the other way, use .encode()
:
s = "text"
b = s.encode("utf-8")
This is helpful before writing to binary files or transmitting via sockets.
Python Bytes to Integer
You can convert bytes to integers using int.from_bytes()
:
b = b"\x00\x10"
num = int.from_bytes(b, byteorder="big")
print(num) # 16
This is used in low-level protocol decoding and binary formats.
Python Bytes and Memory Efficiency
Bytes objects are more memory-efficient than strings when dealing with binary content. They use less overhead and are better suited for performance-critical operations like cryptographic hashing or image processing.
Python Byte Array Use Cases
Use a Python byte array when:
- You need to mutate byte data
- You're building packets for custom protocols
- You require memory-efficient buffers
For instance, compression libraries often accept or return byte arrays.
Python bytes provide a fast and reliable way to handle binary data. You can convert between strings and bytes easily using .encode()
and .decode()
. When you need mutability, use bytearray
. Understanding how Python handles bytes helps you avoid errors like "can't concat str to bytes" and gives you tools to write cleaner, more efficient code.
You can safely manage file I/O, network operations, and low-level system interactions with bytes and byte arrays. These types are core to Python’s ability to work across text and binary worlds efficiently.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.