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?
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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With