python base64.b64decode报错 a bytes-like object is required, not ‘str‘

python base64.b64decode报错 a bytes-like object is required, not ‘str’

base64.b64decode()

base64.b64decode()方法主要作用是对经过base64编码的bytes-like对象或者ASCII字符串进行解码。
使用base64编码类似字节的对象 s,并返回一个字节对象。

b64decode(s, altchars=None, validate=False):
  • s:要被解码的对象
  • altchars:必须是长度为2的bytes-like类型对象或ASCII字符串,它指定“+”和“/”字符的替代字母表。 可选 altchars 应该是长度为2的字节串,它为’+‘和’/'字符指定另一个字母表。
  • validate:

用法:

import base64

mystr = "人生苦短,我用Python"
#byte类型对象
mystr = bytes(mystr,encoding="utf-8")
a = base64.b64encode(mystr)

python3.x中字符都为unicode编码,而b64encode函数的参数为byte类型,所以必须先转码
转码可以使用encode()函数,也可以使用bytes函数,如bytes(usr_pwd,encoding = ‘utf-8’)和usr_pwd.encode(‘utf-8’)二者效果是一样的!

另外注意,b64encode返回的结果也是byte类型,需要我们调decode()

plain_str = "xxx"
auth_plain = base64.b64decode(bytes(plain_str, encoding='utf-8')).decode()

直接使用字符串编码会报错TypeError: a bytes-like object is required, not ‘str‘

Python:直接使用字符串编码会报错TypeError: a bytes-like object is required, not ‘str‘(原因:python3中字符都为unicode编码,而b64encode函数的参数为byte类型,所以需要先转码),先编码成 ‘utf-8‘

base64.b64encode(s) 对字符串进行编码
base64.b64decode(s) 对字符串进行解码

这两个函数参数和返回在python3.x 中都是byte

python bytes和str两种类型可以通过函数encode()和decode()相互转换,
str→bytes:encode()方法。str通过encode()方法可以转换为bytes。
bytes→str:decode()方法。如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法。

猜你喜欢

转载自blog.csdn.net/inthat/article/details/128603980