Explain Codes LogoExplain Codes Logo

Builtins.typeerror: must be str, not bytes

python
error-handling
python-3
typeerror
Anton ShumikhinbyAnton Shumikhin·Jan 9, 2025
TLDR
# To fix `TypeError: must be str, not bytes`, turn those bytes into a string with `.decode()`. # Fix example bytes_obj = b'binary data' fixed_str = bytes_obj.decode() # Defaults to 'utf-8', but the world's your unicode oyster combined = 'String plus ' + fixed_str print(combined) # No TypeError is raised here, TypeError has left the chat

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.

with open('data.txt', 'wb') as file: file.write(b'Hello, bytes!') # No errors here, bytes were invited

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.

with open('data.txt', 'w') as file: file.buffer.write(b'Hello, bytes!') # Writes bytes to a text stream

Get a translator

Utilize your .decode() method whenever you need to swagger as str from binary land.

binary_boogie = b'Boogie in bytes.' str_shimmy = binary_boogie.decode('utf-8')

Handling encoded invites

When dealing with base64 encoded data, decode it first to bytes before signing off.

import base64 encoded_bass = base64.b64encode(b'Bass to encode') with open('data.bin', 'wb') as file: file.write(encoded_bass) # Writes encoded data as bytes

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.

try: some_string_operation(b'byte boogie') except TypeError: print('DJ Error, you’re on!') # When TypeError comes to crash the party

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.