How to encode text to base64 in python

I am trying to encode a text string to base64.

i tried doing this :

name = "your name"
print('encoding %s in base64 yields = %s\n'%(name,name.encode('base64','strict')))

But this gives me the following error:

LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

How do I go about doing this ? ( using Python 3.4)


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

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

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

import base64
base64.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.