I use this small program on my Raspberry Pi to recieve a string sent by my arduino.

import time
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

def check_for_command():
    bytestoread = ser.inWaiting()
    if bytestoread != 0:
        temp = ser.read(bytestoread)

while 1:

the code on the arduino is rather simple:

void setup(){

void loop(){
Serial.println(“Hello Pi”);

the annoying part is. I recieve this:

b'Hello Pi\r\n'

instead of the clean

Hello Pi

How do I get rid of those extra bits without using a list for each character.

Thank in advance!

  • The python code does not need to be anywhere near this complicated. Once you open the device to the handle ser, then all you need is -- linenin=ser.readline() --- and it is good that you are using -- Serial.println -- on the Arduino that sends the \n character at the end of the string so it will work just fine. Then all you need in Python is -- print linein -- to see what you have received. Nothing complicated is required. Just treat it like a file, and remember that ser.readline() is a blocking function. It will stop everything and wait for input.
    – SDsolar
    Jul 17, 2017 at 4:11

3 Answers 3


The b prefix in Python 3 just means that it is a bytes literal. It's not part of the output, that's just telling you the type.

The \r\n is a common Carriage-Return and Newline line-ending characters. You can remove that from your string by calling strip().

Since these are floating-point numbers being returned, I'm guessing you're going to want to use them in some way after they are read, too:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   value = float(ser.readline().strip())
   print('New value is {0:0.2f}'.format(value))

See also:

  • trying to use your lines it gives me a format error on the last line. just before the .format Jul 16, 2017 at 18:23
  • Can you copy and paste the exact error?
    – Ameer
    Jul 16, 2017 at 18:36
  • fixed that error found a new one that sometimes occurs, the first problem was: I am using python 3 so print needs brackets. :) the other error is when by accident serial chains two numbers: ValueError: could not convert string to float: b'21.020.5' Jul 16, 2017 at 18:52
  • I have updated my code to include python 3 style prints.
    – Ameer
    Jul 16, 2017 at 18:57
  • and now you suggest a try and catch to avoid the ValueError? Jul 16, 2017 at 19:01

Use this line

temp = ser.readline(bytestoread).decode('ascii')

instead of

temp = ser.read(bytestoread)

As the bytes sent by Raspbian is encoded in UTF-8, use the following line in order to avoid a strip() at a later-on stage:

temp = ser.read(bytestoread).decode('utf-8')
  • Well, it's not the Raspi sending but the Arduino. And decode() does not strip the '\r\n' from the decoded string. Dec 12, 2019 at 7:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.