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

14,915

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='
>>> 
Share:
14,915
nurtul
Author by

nurtul

Updated on June 04, 2022

Comments

  • nurtul
    nurtul almost 2 years

    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.

  • nurtul
    nurtul almost 11 years
    and to decode you do s2 = base64.b64decode(s.decode('ascii'))??
  • agf
    agf almost 11 years
    No, you decode outside of the b64decode: base64.b64decode(s2).decode('ascii') is '12345'
  • ratna
    ratna almost 11 years
    Thank you very much. This helped