【问题标题】:How to convert from Base64 to string Python 3.2 [duplicate]如何从 Base64 转换为字符串 Python 3.2 [重复]
【发布时间】:2012-11-07 01:44:55
【问题描述】:

可能重复:
Converting a string to and from Base 64

def convertFromBase64 (stringToBeDecoded):
    import base64
    decodedstring=str.decode('base64',"stringToBeDecoded")
    print(decodedstring)
    return

convertFromBase64(dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=)

我想要获取一个 base64 编码的字符串并将其转换回原始字符串,但我不知道出了什么问题

我收到了这个错误

 Traceback (most recent call last):
 File "C:/Python32/junk", line 6, in <module>
convertFromBase64(("dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE="))
 File "C:/Python32/junk", line 3, in convertFromBase64
decodedstring=str.decode('base64',"stringToBeDecoded")
AttributeError: type object 'str' has no attribute 'decode'

【问题讨论】:

  • 请现在用你的进度更新你的问题,而不是发布涵盖相同内容的内容
  • 您在stackoverflow.com/questions/13261802/… 上得到的评论是正确答案。你本可以发表评论要求澄清

标签: python-3.x base64


【解决方案1】:

字符串已经被“解码”,因此 str 类没有“解码”功能。因此:

AttributeError: type object 'str' has no attribute 'decode'

如果你想解码一个字节数组并把它变成一个字符串调用:

the_thing.decode(encoding)

如果你想编码一个字符串(把它变成一个字节数组)调用:

the_string.encode(encoding)

就 base 64 的东西而言: 使用 'base64' 作为上述编码的值会产生错误:

LookupError: unknown encoding: base64

打开控制台并输入以下内容:

import base64
help(base64)

你会看到base64有两个非常方便的函数,分别是b64decode和b64encode。 b64 decode 返回一个字节数组,b64encode 需要一个字节数组。

要将字符串转换为 base64 表示,您首先需要将其转换为字节。我喜欢 utf-8,但使用你需要的任何编码......

import base64
def stringToBase64(s):
    return base64.b64encode(s.encode('utf-8'))

def base64ToString(b):
    return base64.b64decode(b).decode('utf-8')

【讨论】:

  • 对于遇到这个问题的任何人,使用“latin-1”对于德语特殊字符会派上用场(如提到的“无论您需要什么编码”)
猜你喜欢
  • 2018-06-27
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2014-04-13
  • 2013-04-19
  • 1970-01-01
相关资源
最近更新 更多