简体   繁体   English

python是否相当于Javascript的'btoa'

[英]Does python have an equivalent to Javascript's 'btoa'

I'm trying to find an exact equivalent to javascript's function 'btoa', as I want to encode a password as base64. 我试图找到与javascript函数'btoa'完全相同的函数,因为我想将密码编码为base64。 It appears that there are many options however, as listed here: 看来有很多选项,如下所示:

https://docs.python.org/3.4/library/base64.html https://docs.python.org/3.4/library/base64.html

Is there an exact equivalent to 'btoa' in python? 在python中是否有与'btoa'完全相同的东西?

Python's Base64 : Python的Base64

import base64

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

# value of encoded is SGVsbG8gV29ybGQh

Javascript's btoa : Javascript的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' 我尝试了python代码并得到(使用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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM