Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 223
Tom Avatar asked Jul 17 '17 18:07

Tom


Video Answer


2 Answers

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.

like image 144
Willem Van Onsem Avatar answered Oct 22 '22 06:10

Willem Van Onsem


A simple .decode("utf-8") would do

import base64
string = base64.b64encode(bytes("string", 'utf-8'))
print (string.decode("utf-8"))
like image 45
Sriram Sitharaman Avatar answered Oct 22 '22 07:10

Sriram Sitharaman