【问题标题】:How to base64 encode/decode a variable with string type in Python 3?如何在 Python 3 中对字符串类型的变量进行 base64 编码/解码?
【发布时间】:2013-06-04 18:27:36
【问题描述】:

它给了我一个错误,编码的行需要是字节而不是 str/dict

我知道在文本之前添加一个“b”会解决这个问题并打印编码的东西。

import base64
s = base64.b64encode(b'12345')
print(s)
>>b'MTIzNDU='

但是如何对变量进行编码呢? 比如

import base64
s = "12345"
s2 = base64.b64encode(s)
print(s2)

添加和不添加 b 都会给我一个错误。我不明白

我也在尝试使用 base64 编码/解码字典。

【问题讨论】:

    标签: python dictionary base64 decode encode


    【解决方案1】:

    您需要对 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='
    >>> 
    

    【讨论】:

    • 和解码你做 s2 = base64.b64decode(s.decode('ascii'))??
    • 不,你在b64decode之外的decodebase64.b64decode(s2).decode('ascii')'12345'
    • 非常感谢。这有帮助
    猜你喜欢
    • 2012-11-13
    • 1970-01-01
    • 2021-08-23
    • 2011-10-31
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多