Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode/decode a variable with string type in Python 3?

It gives me an error that the line encoded needs to be bytes not str/dict

I know of adding a "b" before the text will solve that and print the encoded thing.

import base64
s = base64.b64encode(b'12345')
print(s)
>>b'MTIzNDU='

But how do I encode a variable? such as

import base64
s = "12345"
s2 = base64.b64encode(s)
print(s2)

It gives me an error with the b added and without. I don't understand

I'm also trying to encode/decode a dictionary with base64.

like image 761
nurtul Avatar asked Jun 08 '13 15:06

nurtul


1 Answers

You need to encode the unicode string. If it's just normal characters, you can use ASCII. If it might have other characters in it, or just for general safety, you probably want utf-8.

>>> import base64
>>> s = "12345"
>>> s2 = base64.b64encode(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ". . . /lib/python3.3/base64.py", line 58, in b64encode
    raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str
>>> s2 = base64.b64encode(s.encode('ascii'))
>>> print(s2)
b'MTIzNDU='
>>> 
like image 140
agf Avatar answered Sep 22 '22 17:09

agf