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!
source to share
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.
source to share