Builtins.typeerror: must be str, not bytes
Note: Use bytes.decode()
to convert bytes to str for concatenation. TypeError is not invited to this party.
When do you meet TypeError?
This sneaky TypeError
"must be str, not bytes," appears when you try performing a string operation on bytes
, forgetting to convert it first. Being str
and bytes
are two separate parties in Python, sending an invite to the wrong one can result in a huge bummer.
Fixing the party foul
Write bytes, not invites
In Python 3, always use 'wb' (write binary) to scribble down bytes to a file.
Read the party lists
Remember to use 'rb' (read binary) when parsing through your list of binary arrivals.
Buffer is the bouncer
Use buffer
as part of the security when accessing binary streams under text skies.
Get a translator
Utilize your .decode()
method whenever you need to swagger as str from binary land.
Handling encoded invites
When dealing with base64 encoded data, decode it first to bytes before signing off.
How to become a party animal
Are you speaking my language?
Always specify your encodings. You don’t want to end up at a salsa party when you’re in a moonwalk mood.
Python 2 vs 3: Party Evolution
When flipping your jam from Python 2 to Python 3, double-check your string and byte dances. Python 3 doesn't accept freestyle here.
DJ Error on the deck
Wrap those risky moves in try-except blocks to catch and redirect TypeError
from the main floor to backstage.
Party poopers to avoid
- Showing up in 'w' mode at a 'wb' party in Python 3.
- Assuming the DJ plays 'utf-8' tunes all night long at the
.decode()
party. - Forgetting to play the
.buffer
track when dealing with a crowd that’s byte-curious.
Was this article helpful?