如何从Base64转换为Python 3.2字符串

问题描述:

可能重复:
将字符串与Base 64相互转换

Possible Duplicate:
Converting a string to and from Base 64

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

convertFromBase64(dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=)

我想使用base64编码的字符串并将其转换回原始字符串,但我无法弄清楚到底是什么问题

I am tying to take a base64 encoded string and convert it back to the original string but I cant figure out quite what is wrong

我收到此错误

 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'

字符串已被解码",因此str类没有解码"功能.因此:

A string is already 'decoded', thus the str class has no 'decode' function.Thus:

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

如果要解码字节数组并将其转换为字符串调用:

If you want to decode a byte array and turn it into a string call:

the_thing.decode(encoding)

如果要编码字符串(将其转换为字节数组),请调用:

If you want to encode a string (turn it into a byte array) call:

the_string.encode(encoding)

就基础64项而言: 使用"base64"作为上面的编码值会产生错误:

In terms of the base 64 stuff: Using 'base64' as the value for encoding above yields the error:

LookupError: unknown encoding: base64

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

Open a console and type in the following:

import base64
help(base64)

您将看到base64具有两个非常方便的功能,即b64decode和b64encode. b64解码返回一个字节数组,b64encode需要一个字节数组.

You will see that base64 has two very handy functions, namely b64decode and b64encode. b64 decode returns a byte array and b64encode requires a bytes array.

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

To convert a string into it's base64 representation you first need to convert it to bytes. I like utf-8 but use whatever encoding you need...

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

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