user4861730
user4861730

Reputation:

encoding decoding string in python 3.6 doesn't work?

I have this code:

import base64
words = ('word1',"word2")

for word in words: #for loop
    str_encoded = base64.b64encode(word.encode())  # encoding it
    print(str_encoded)    #print encoded
    str_decoded = str_encoded.decode('utf-8')
    print(str_decoded)
    back = base64.standard_b64decode(str_decoded)  # testing if it worked
    print(word, "," ,"{{" , str_decoded  , "}}" , "," , str_decoded, back)  #print test

when i print the test i see the b' wasn't removed.

how can i remove it? thanks!

Upvotes: 1

Views: 439

Answers (2)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You tried to decode your data in the wrong order, you have to go backwards compared to the encoding order:

import base64

words = ('word€',"word2") # Added some non-ascii characters for testing

for word in words:

    # Encoding

    print("Word:", word)
    utf8_encoded = word.encode('utf8') # Encoding in utf8, gives a bytes object
    print('utf8 encoded:', utf8_encoded)
    str_encoded = base64.b64encode(utf8_encoded)  # Encoding it in B64
    print("Base64 encoded:", str_encoded)    

    # Decoding

    b64_decoded = base64.standard_b64decode(str_encoded)  # Decoding from B64, we get a bytes object
    print("Decoded from base64:", b64_decoded) 
    str_decoded = b64_decoded.decode('utf-8') # and decode it (as utf8) to get a string
    print("Decoded string:", str_decoded, '\n')

Output:

Word: word€
utf8 encoded: b'word\xe2\x82\xac'
Base64 encoded: b'd29yZOKCrA=='
Decoded from base64: b'word\xe2\x82\xac'
Decoded string: word€ 

Word: word2
utf8 encoded: b'word2'
Base64 encoded: b'd29yZDI='
Decoded from base64: b'word2'
Decoded string: word2 

Upvotes: 1

Klemen Koleša
Klemen Koleša

Reputation: 446

You have to decode "back" variable (which in your case is bytes) with:

back.decode("utf-8")

print(str(word), "," ,"{{" , str_decoded  , "}}" , "," , str_decoded, back.decode("utf-8") )

Upvotes: 0

Related Questions