I'm trying to find an exact equivalent to javascript's function 'btoa', as I want to encode a password as base64. It appears that there are many options however, as listed here:
https://docs.python.org/3.4/library/base64.html
Is there an exact equivalent to 'btoa' in python?
btoa(): accepts a string where each character represents an 8bit byte. If you pass a string containing characters that cannot be represented in 8 bits, it will probably break. Probably that's why btoa is deprecated.
Python 3 provides a base64 module that allows us to easily encode and decode information. We first convert the string into a bytes-like object. Once converted, we can use the base64 module to encode it.
b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.
b64encode() in Python. With the help of base64. b64encode() method, we can encode the string into the binary form. Return : Return the encoded string.
Python's Base64:
import base64
encoded = base64.b64encode(b'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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With