Convert ascii string to base64 without "b" and quotes

I wanted to convert an ascii string (well, just text to be precise) towards base64. So I know how to do it, I just use the following code:

import base64
string = base64.b64encode(bytes("string", 'utf-8'))
print (string)

      

What gives me

b'c3RyaW5n'

      

However, the problem is that I would like to just print

c3RyaW5n

      

Can I print a string without quotes "b" and ""? Thank!

+3


source to share


2 answers


The prefix b

means it is a binary string . A binary string is not a string: it is a sequence of bytes (values ​​ranging from 0 to 255). It is simply typed as a string to make it more compact.

However, in the case of base64, all characters are valid ASCII characters, so you can simply decode it like this:



print(string.decode('ascii'))

      

So here we are going to decode each byte to its ASCII equivalent. Since base64 makes sure that every byte it produces is in the ASCII range of 'A'

up to '/'

), we'll always output a valid string. However, be aware that this is not guaranteed with an arbitrary binary string.

+5


source


Simple .decode("utf-8")

will do



import base64
string = base64.b64encode(bytes("string", 'utf-8'))
print (string.decode("utf-8"))

      

-1


source







All Articles