Converting a string to and from Base 64 [duplicate] Converting a string to and from Base 64 [duplicate] python-3.x python-3.x

Converting a string to and from Base 64 [duplicate]


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 base64help(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 base64def stringToBase64(s):    return base64.b64encode(s.encode('utf-8'))def base64ToString(b):    return base64.b64decode(b).decode('utf-8')