TypeError: Can't convert 'bytes' object to str implicitly


Error:

Traceback (most recent call last):
  File "b64-str.py", line 10, in <module>
    print('\nstring is\n' + so)
TypeError: Can't convert 'bytes' object to str implicitly


Problem Code:

so = base64.b64decode(b64)
print('\nstring is\n' + so)


Solution:

so = base64.b64decode(b64).decode('utf-8', 'ignore')
print('\nstring is\n' + so)

This Python 3 error happens when you join bytes and str with the plus operator. Python 3 keeps bytes and text strictly separate, so they cannot be concatenated directly.

Calling .decode() on the bytes, or .encode() on the string, converts one to the other so the types match. This is one of the most common surprises when moving code from Python 2 to Python 3.

Comments

Popular posts from this blog

[Solved] Error: No such keg: /usr/local/Cellar/gcc

[How To] Unfollow Non-followers on Instagram