0

At the moment I have a byte stream of a string that is received by my Python code and must be converted into a string. For now I managed to extract each character, convert them and append them to a string individually. The code looks something like this:

import struct

# The byte stream is received and stored in byte_stream

text = ''
i = 0
while i < len(byte_stream):
    text = text + struct.unpack('c', byte_stream[i])[0]
    i += 1

print(text)

But that surely cannot be the most efficient way... Is there a more elegant way to do achieve the same result?

Max Z.
  • 801
  • 1
  • 9
  • 25

1 Answers1

1

From Convert bytes to a Python string:

byte_stream = [112, 52, 52]
''.join(map(chr, bytes))
>> p44
Community
  • 1
  • 1
Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
  • On that page I found the following code that worked :) Many thanks `byte_stream.decode('utf-8')` I cannot believe I didn't find that out myself... – Max Z. Jan 22 '16 at 00:30