2012-11-07 53 views
2

Possible Duplicate:
Converting a string to and from Base 64如何從Base64編碼轉換爲字符串的Python 3.2

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' 
+0

請現在就更新你對你的進步,而不是發佈的內容覆蓋同樣的事情 – Sheena

+0

在http有註釋的問題://計算器.com/questions/13261802 /轉換字符串與從基地64是正確的答案。你可以發表評論,要求澄清 – Sheena

回答

17

的字符串已經「解碼」,所以str類沒有「解碼」 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') 
+0

對於任何人來這個問題,使用「拉丁-1」將派上用場德國特殊字符(如提到「任何你需要的編碼」) – Kev1n91

相關問題