2012-11-07 274 views
10

我正在尝试编写两个程序,一个将字符串转换为base64,然后是另一个需要base64编码的字符串并将其转换回字符串的程序。
到目前为止,我不能让过去的base64编码部分,因为我不断收到错误将字符串转换为64位的字符串

TypeError: expected bytes, not str 

我的代码看起来像这样,到目前为止

def convertToBase64(stringToBeEncoded): 
import base64 
EncodedString= base64.b64encode(stringToBeEncoded) 
return(EncodedString) 
+5

因为python-3有unicode字符串,所以引入了字节数据类型。您必须将您的字符串转换为一个字节数组,例如通过使用'b = bytes(mystring,'utf-8')',然后使用'b'作为编码:'EncodedString = base64.b64encode(b)',它将返回一个字节数组 –

回答

25

的字符串已经“解码”,因此海峡类没有“解码” function.Thus:

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

如果要解码的字节数组,并把它变成一个字符串电话:

the_thing.decode(encoding) 

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

the_string.encode(encoding) 

在基部64的东西的术语: 使用“的base64”作为以上的产率编码的值错误:

LookupError: unknown encoding: base64 

开启在下面的一个控制台和类型:

import base64 
help(base64) 

你会看到base64有两个非常方便的功能,即b64decode和b64encode。 b64解码返回一个字节数组,并且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')