Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from Base64 to string Python 3.2 [duplicate]

Possible Duplicate:
Converting a string to and from Base 64

def convertFromBase64 (stringToBeDecoded):
    import base64
    decodedstring=str.decode('base64',"stringToBeDecoded")
    print(decodedstring)
    return

convertFromBase64(dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=)

I am tying to take a base64 encoded string and convert it back to the original string but I cant figure out quite what is wrong

I am getting this error

 Traceback (most recent call last):
 File "C:/Python32/junk", line 6, in <module>
convertFromBase64(("dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE="))
 File "C:/Python32/junk", line 3, in convertFromBase64
decodedstring=str.decode('base64',"stringToBeDecoded")
AttributeError: type object 'str' has no attribute 'decode'
like image 510
spenman Avatar asked Nov 07 '12 01:11

spenman


People also ask

How do I decode a base64 string in Python?

To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.

What is base64 b64decode in Python?

b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.


1 Answers

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')
like image 129
Sheena Avatar answered Oct 12 '22 01:10

Sheena