Concatenate byte with string in Python 3.5.2


I am making an application where I detect data from a sensor from Arduino and I want to print them together with the date and time. The data I read from the Arduino serial port is byte type, while the date and time are str.

I want to concatenate these data to print them with this line of code:

temperatura = ser.readline()

time_hhmmss = time.strftime('%H:%M:%S')
date_mmddyyyy = time.strftime('%d/%m/%Y')

print(temperatura + ',' + time_hhmmss + ',' + date_mmddyyyy)

But this error throws me: TypeError: can not concate bytes to str

I've looked for a way to concatenate them but I can not achieve it. I indicate that the data if I capture it from Arduino. I await your help. Thanks.

asked by Juan Sánchez 28.09.2016 в 08:30

2 answers


It's as simple as converting from bytes to str (by default, coded in utf-8 ):

print(temperatura.decode() + ',' + time_hhmmss + ',' + date_mmddyyyy)

Although it can be improved a little more:

from datetime import datetime

temperatura = ser.readline()

print("{} ºC, {:%H:%M:%S, %d/%m/%Y}".format(temperatura.decode(),
answered by 28.09.2016 / 10:40

Try this way of concatenating, it should work in both Python 3 and Python 2:

answered by 28.09.2016 в 08:46