0

Consider the following Python code:

payload = """{"id": "866425038985380","ts": "2020-05-07T13:16:51.350Z"}"""
ascii_message = payload.encode('ascii')
encoded_payload = base64.b64encode(ascii_message)
string_payload = str(encoded_payload)
print(string_payload)
print(type(encoded_payload))

When I print the lines above, my output is:

b'eyJpZCI6ICI4NjY0MjUwMzg5ODUzODAiLCJ0cyI6ICIyMDIwLTA1LTA3VDEzOjE2OjUxLjM1MFoifQ=='
<class 'bytes'>

Is it possible to get a string equivalent of the encoded result? In particular, how can I get this:

'eyJpZCI6ICI4NjY0MjUwMzg5ODUzODAiLCJ0cyI6ICIyMDIwLTA1LTA3VDEzOjE2OjUxLjM1MFoifQ=='

I'd like to set that to a new variable without the b in front and for it to type string.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
ENV
  • 877
  • 2
  • 10
  • 32
  • 1
    Does this answer your question? [Convert bytes to a string](https://stackoverflow.com/questions/606191/convert-bytes-to-a-string) – Ayush Garg Jun 27 '21 at 17:50
  • 1
    `string_payload = base64.b64encode(ascii_message).decode('ascii')` – Epsi95 Jun 27 '21 at 17:54
  • The `b"..."` is not actually in the data. (Take its `len()` if you doubt that.) What you are seeing is Python's technical representation of a bytestring, which is a bunch of 8-bit quantities. They differ from Python strings which are always Unicode, and the `b` is to show you which is which, much as `2.0` shows you that you are dealing with a float. Use the bytestring as is. Binary files, network protocols and encryption libraries will happily accept it because it is what they are expecting. – BoarGules Jun 27 '21 at 17:58
  • @BoarGules , is there a way to retrieve just that bytestring then? – ENV Jun 27 '21 at 19:14
  • That *is* the bytestring. Just use it. By default Python displays bytestrings with a `b` prefix just as it displays lists with square brackets and commas. They are not really in the data either. – BoarGules Jun 27 '21 at 19:18

0 Answers0