Python使用base64进行转码时,发现打印的字符串带有b'xxxx'
import base64
username="admin"
password="lian2020"
aa=base64.b64encode(username.encode("utf-8"))
print (aa)
bb=base64.b64encode(password.encode("utf-8"))
print (bb)
打印结果:# 得到的编码结果前带有 b
b'YWRtaW4='
b'bGlhbjIwMjA='
网上查到资料:
Python3的字符串的编码语言用的是unicode编码,由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干字节,如果要在网络上传输,或保存在磁盘上就需要把str变成以字节为单位的bytes.
解决方法:
用str再转换一次,# 去掉编码结果前的 b
username="admin"
password="lian2020"
aa=base64.b64encode(username.encode("utf-8"))
print (aa)
print (str(aa,'utf-8'))
bb=base64.b64encode(password.encode("utf-8"))
print (str(bb))
print (str(bb,'utf-8'))
执行结果,正常输出。
b'YWRtaW4='
YWRtaW4=
b'bGlhbjIwMjA='
bGlhbjIwMjA=
参考: