TypeError
TypeError: a bytes-like object is required, not 'str'
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
print("found")
TypeError: a bytes-like object is required, not 'str'What causes this error
An operation received a str where bytes were expected, or bytes where str was expected. Python 3 enforces strict separation between text (str) and binary data (bytes).
How to fix it
Encode strings to bytes: `s.encode('utf-8')`. Decode bytes to strings: `b.decode('utf-8')`. Open files in the correct mode ('r' for text, 'rb' for binary). Match types consistently.
Code that causes this error
with open("data.bin", "rb") as f:
content = f.read()
if "header" in content: # content is bytes
print("found")Fixed code
with open("data.bin", "rb") as f:
content = f.read()
if b"header" in content: # use bytes literal
print("found")About TypeError
This TypeError occurs when a function or operation expects bytes but receives a string (str), or vice versa. In Python 3, strings and bytes are strictly separate types: `str` holds Unicode text and `bytes` holds raw binary data. This error commonly appears when reading files opened in binary mode ('rb') and comparing with string literals, when working with sockets (which send/receive bytes), and when using regular expressions with the wrong type.
The fix is straightforward: encode strings to bytes with `.encode('utf-8')`, or decode bytes to strings with `.decode('utf-8')`. When opening files, choose text mode (no 'b') for text data and binary mode ('rb'/'wb') for binary data. The `io` module provides wrappers to convert between text and binary streams.
Common scenarios
Performing operations between incompatible types like strings and integers
Calling methods that return None and chaining operations on the result
Passing the wrong number or type of arguments to a function
Using bracket notation on objects that do not support indexing