简体   繁体   中英

Python readline() returns string that wont convert to int or float

I am using Arduino SoftwareSerial library to send serial data to a Raspberry Rx pin. I can get the Arduino serial data sent over to the Raspberry successfully, in as much that the integers I sent arrive as the equivalent in a string.

The problem:

I am trying to convert the string that the .readline() returns into a float or int, but I am unable to do so.

import serial
oSer = serial.Serial("/dev/ttyAMA0",baudrate=57600,timeout=1)

while True:
    sInput = oSer.readline()
    print sInput #Returns: >>1,2,3,

    lsInput = sInput.split(',')
    print lsInput #Returns: >>['1','2','3','\r\n']

How can I convert this to an int or float? I simply need to do some arithmetic with the numbers. I have tried:

    lfInput = [float(i) for i in lsInput] #Returns: >> ValueError: could not convert to float:

    liInput = [int(i) for i in lsInput] #Returns: >> ValueError: invalid literal for int() with base 10: ''

The Answer

Thanks to John and Padraic who provided Answers, I can confirm an update on how to fix the above problem. I prefer Padraic's solution, slightly more elegant, but either work. I added the following:

John's and especially Pad's solution (see answers below for better and more detail):

sInput = oSer.readline().strip() #but see answers below from Pad for more detail

The error is caused by the \\r\\n at the end of the line. int() and float() don't like that.

You can either strip it off like so:

sInput = oSer.readline().strip()

Or you can modify the loop to ignore non-numbers:

liInput = [int(i) for i in lsInput if i.isdigit()]

You can rstrip the trailing white space:

while True:
    sInput = oSer.readline().rstrip().split(",")

Or a more robust approach is to see if an element can be cast to a float using a try/except:

def cast(it):
    for ele in it:
        try:
            yield float(ele)
        except ValueError:
            pass


while True:
    sInput = oSer.readline().rstrip(",\r\n").split(",")
    nums = list(cast(sInput.split(",")))

cast will work for floats, ints and negative numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM