Does python have an equivalent to Javascript's 'btoa'

Python's Base64:

import base64

encoded = base64.b64encode('Hello World!')
print encoded

# value of encoded is SGVsbG8gV29ybGQh

Javascript's btoa:

var str = "Hello World!";
var enc = window.btoa(str);

var res = enc;

// value of res is SGVsbG8gV29ybGQh

As you can see they both produce the same result.


I tried the python code and got (with python3) TypeError: a bytes-like object is required, not 'str'

When I added the encode it seems to work

import base64

dataString = 'Hello World!'
dataBytes = dataString.encode("utf-8")
encoded = base64.b64encode(dataBytes)

print(encoded)  # res=> b'SGVsbG8gV29ybGQh'

Tags:

Python

Base64