Search code examples
pythonpython-3.xencodingbase64

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)


Solution

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

    import base64
    b = base64.b64encode(bytes('your_string', 'utf-8')) # bytes
    base64_str = b.decode('utf-8') # convert bytes to string
    

    Explanation:

    The bytes function creates a bytes object from the string "your_string" using UTF-8 encoding. In Python, bytes represents a sequence of bits and UTF-8 specifies the character encoding to use.

    The base64.b64encode function encodes bytes object into Base64 format. It takes a bytes-like object as input and returns a Base64 encoded bytes object.

    The b.decode function decodes the bytes object (here b) using UTF-8 encoding and returns the resulting string. It converts the bytes back to their original string representation.