Harry Boy
Harry Boy

Reputation: 4767

How to convert base 64 encoded string back to original string again in python

I have a string that I need to convert to base64 and send it over json via a REST API.

import base64

#Original string
my_string = "my_string"           #debugger=my_string

#Convert to bytes so I can base64 it
my_string_to_bytes = my_string.encode()   #debugger=b'my_string'

#Base64 it
my_string_to_bytes_to_base64 = base64.b64encode(my_string_to_bytes) #debugger = {bytes} b'bXlfc3RyaW5n'

#Convert to string or I get error TypeError: Object of type 'bytes' is not JSON serializable
my_string_to_bytes_to_base64_to_str = str(my_string_to_bytes_to_base64) #debugger = {str} b'bXlfc3RyaW5n'

This works and the data gets sent over the REST to my C# client and written to a text file. Now the C# client sends the exact same data back again from text file. I want to convert this back again to get the original string I started with. So I start with my_string_to_bytes_to_base64_to_str

back_to_bytes = str.encode(my_string_to_bytes_to_base64_to_str) #debugger = {bytes} b"b'bXlfc3RyaW5n'"

But in the debugger this appends an extra 'b' onto the start of it:

b"b'bXlfc3RyaW5n'"

How can I convert the data back again to get "my_string"?

Upvotes: 0

Views: 1255

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308402

In this case, str(x) isn't doing what you think it is. It's not converting a byte string to a regular string, it's creating a string representation of the byte object.

To convert a byte string to a regular string, use the decode method. You may need to include a parameter to specify the encoding of the byte string, but in your specific case it should all be ASCII which is the default.

my_string_to_bytes_to_base64_to_str = my_string_to_bytes_to_base64.decode()

Upvotes: 1

Related Questions