nur*_*tul 5 python base64 dictionary encode decode
它给出了一个错误,即编码的行必须是字节而不是str/dict
我知道在文本解决之前添加"b"并打印编码的东西.
import base64
s = base64.b64encode(b'12345')
print(s)
>>b'MTIzNDU='
Run Code Online (Sandbox Code Playgroud)
但是我如何编码变量呢?如
import base64
s = "12345"
s2 = base64.b64encode(s)
print(s2)
Run Code Online (Sandbox Code Playgroud)
添加和不添加b会给我一个错误.我不明白
我也试图用base64编码/解码字典.
您需要对unicode字符串进行编码.如果它只是普通字符,则可以使用ASCII.如果它可能有其他字符,或者只是为了一般安全,你可能想要utf-8
.
>>> import base64
>>> s = "12345"
>>> s2 = base64.b64encode(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ". . . /lib/python3.3/base64.py", line 58, in b64encode
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
TypeError: expected bytes, not str
>>> s2 = base64.b64encode(s.encode('ascii'))
>>> print(s2)
b'MTIzNDU='
>>>
Run Code Online (Sandbox Code Playgroud)