22

I am trying to write two programs one that converts a string to base64 and then another that takes a base64 encoded string and converts it back to a string.
so far i cant get past the base64 encoding part as i keep getting the error

TypeError: expected bytes, not str

my code looks like this so far

def convertToBase64(stringToBeEncoded):
import base64
EncodedString= base64.b64encode(stringToBeEncoded)
return(EncodedString)
spenman
  • 653
  • 3
  • 7
  • 11
  • 7
    Since python-3 has unicode string, the bytes datatype was introduced. You have to convert your string to a bytearray, e.g. by using `b = bytes(mystring, 'utf-8')`, and then using `b` for the encoding: `EncodedString = base64.b64encode(b)`, which will return a bytearray – Andreas Wallner Nov 07 '12 at 01:14
  • 1
    This same problem plagued me for most of a day, until I stumbled across this little nugget: https://stackabuse.com/encoding-and-decoding-base64-strings-in-python/ (I wanted to post an answer here, but the post has been closed as duplicate. Sorry, but the linked post doesn't address this question--even though the answer may be related.) – Jim Fell Jul 20 '23 at 20:11

1 Answers1

51

A string is already 'decoded', thus the str class has no 'decode' function.Thus:

AttributeError: type object 'str' has no attribute 'decode'

If you want to decode a byte array and turn it into a string call:

the_thing.decode(encoding)

If you want to encode a string (turn it into a byte array) call:

the_string.encode(encoding)

In terms of the base 64 stuff: Using 'base64' as the value for encoding above yields the error:

LookupError: unknown encoding: base64

Open a console and type in the following:

import base64
help(base64)

You will see that base64 has two very handy functions, namely b64decode and b64encode. b64 decode returns a byte array and b64encode requires a bytes array.

To convert a string into it's base64 representation you first need to convert it to bytes. I like utf-8 but use whatever encoding you need...

import base64
def stringToBase64(s):
    return base64.b64encode(s.encode('utf-8'))

def base64ToString(b):
    return base64.b64decode(b).decode('utf-8')
Sheena
  • 15,590
  • 14
  • 75
  • 113