How to encode text to base64 in python How to encode text to base64 in python python python

How to encode text to base64 in python


Remember to import base64 and that b64encode takes bytes as an argument.

import base64base64.b64encode(bytes('your string', 'utf-8'))


It turns out that this is important enough to get it's own module...

import base64base64.b64encode(b'your name')  # b'eW91ciBuYW1l'base64.b64encode('your name'.encode('ascii'))  # b'eW91ciBuYW1l'


1) This works without imports in Python 2:

>>>>>> 'Some text'.encode('base64')'U29tZSB0ZXh0\n'>>>>>> 'U29tZSB0ZXh0\n'.decode('base64')'Some text'>>>>>> 'U29tZSB0ZXh0'.decode('base64')'Some text'>>>

(although this doesn't work in Python3 )

2) In Python 3 you'd have to import base64 and do base64.b64decode('...')- will work in Python 2 too.