Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of bytes to a string in Python 3

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?

like image 628
Minifig666 Avatar asked Jun 15 '15 12:06

Minifig666


People also ask

How do I convert a list to a string in Python 3?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Which method is used to convert raw byte data to a string in Python?

Similarly, Decoding is process to convert a Byte object to String. It is implemented using decode() . A byte string can be decoded back into a character string, if you know which encoding was used to encode it.

How do you decode bytes in Python?

Python bytes decode() function is used to convert bytes to string object. Both these functions allow us to specify the error handling scheme to use for encoding/decoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError.

How do you concatenate bytes in Python 3?

The easiest way to do what you want is a + a[:1] . You could also do a + bytes([a[0]]) . There is no shortcut for creating a single-element bytes object; you have to either use a slice or make a length-one sequence of that byte.


1 Answers

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'
like image 119
Alex Taylor Avatar answered Sep 29 '22 04:09

Alex Taylor