Convert a list of bytes to a string in Python 3

10.2k Views Asked by At

I'm writing a program in Python 3.4.1 that uses PySerial to test some hardware.

Bytes are read from the serial port one at a time, and then appended to list. When the list reaches a certain size, it is sent for processing. Depending on the incoming data, the data sometimes has to be processed before the list is full, hence byte-by-byte operation.

The list then comes back as:

[b'F', b'o', b'o']

For part of the test script, I need to be able to convert this to a string, so that I can just print:

Foo

My solution is:

b''.join([b'F', b'o', b'o']).decode("ascii")

But it just feels wrong. Is there a better approach to this?

2

There are 2 best solutions below

0
On

If you don't like how join looks, you can do following:

bytes.join(b'', [b'F', b'o', b'o']).decode('ascii')

It's almost the same thing as in your code. I don't think you'll find any better approach.

2
On

IMO, this is slightly more readable, but I wouldn't complain if I came across your code in review. Tested in Python 2.7:

>>> bytearray([b'F', b'o', b'o']).decode('ascii')
u'Foo'