3

I am trying to convert python3 code into python2 but output seems to be different.

The code in python2 is:

import base64
crypto = 'aGVsbG8=' #=hello
s = base64.b64decode(crypto)
print(s)

It prints what I want: Something like- Cs~as59 whatever

But for python3 the same script prints something like: b'\x45\x67\xe3'

Why am I getting different output for same input?

2
  • 1
    The output of b64decode is a sequence of bytes. In Python 2.x, that's exactly what a string was, so that's what was returned. But in Python 3, strings are now Unicode, so things that are explicitly composed of bytes use a separate bytestring type, indicated by the b prefix. Both of your outputs will be exactly the same data, just shown in two different representations. Commented Jul 23, 2020 at 14:41
  • @jasonharper how would i convert it to the python2 representation. because my script works with 2 but not 3. Commented Jul 23, 2020 at 15:07

1 Answer 1

3

The output of the Base64 decode is now a bytestring, you can use the .decode() function to transform it into a normal string:

import base64
crypto = 'aGVsbG8=' #=hello
s = base64.b64decode(crypto)
print(s.decode("utf-8"))

This should now print the decoded string correctly.

Sign up to request clarification or add additional context in comments.

1 Comment

tthe problem is it i dont think it is utf-8.... if i do utf-8 it gives an error, if i ignore error it discards some of the data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.