6

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.

1 Answer 1

11

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='
>>> 
Sign up to request clarification or add additional context in comments.

2 Comments

and to decode you do s2 = base64.b64decode(s.decode('ascii'))??
No, you decode outside of the b64decode: base64.b64decode(s2).decode('ascii') is '12345'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.