22

重複の可能性:
文字列をBase64との間で変換する

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'
4

1 に答える 1

69

文字列はすでに「デコード」されているため、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 という 2 つの非常に便利な関数があることがわかります。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')
于 2012-11-07T10:16:27.120 に答える