Categories
base64 python python-3.x

Convert ascii string to base64 without the “b” and quotation marks

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

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

Which gives me

b'c3RyaW5n'

However the problem is, I’d like it to just print

c3RyaW5n

Is it possible to print the string without the “b” and the ” quotation marks?
Thanks!

The b prefix denotes that it is a binary string. A binary string is not a string: it is a sequence of bytes (values in the 0 to 255 range). It is simply typesetted as a string to make it more compact.

In case of base64 however, all characters are valid ASCII characters, you can thus simply decode it like:

print(string.decode('ascii'))

So here we will decode each byte to its ASCII equivalent. Since base64 guarantees that every byte it produces is in the ASCII range 'A' to '/') we will always produce a valid string. Mind however that this is not guaranteed with an arbitrary binary string.