简体   繁体   English

Python readline()返回不会转换为int或float的字符串

[英]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. 我正在使用Arduino SoftwareSerial库将串行数据发送到Raspberry Rx引脚。 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. 我可以成功地将Arduino串行数据发送到Raspberry,使我发送的整数与字符串中的等效整数一样多。

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. 我正在尝试将.readline()返回的字符串转换为float或int,但是我无法这样做。

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? 如何将其转换为int或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. 感谢提供答案的John和Padraic,我可以确认有关如何解决上述问题的更新。 I prefer Padraic's solution, slightly more elegant, but either work. 我更喜欢Padraic的解决方案,虽然稍微优雅一些​​,但两者都能起作用。 I added the following: 我添加了以下内容:

John's and especially Pad's solution (see answers below for better and more detail): John的解决方案,尤其是Pad的解决方案(请参见下面的答案以获取更多,更多的信息):

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. 该错误是由行尾\\r\\n引起的。 int() and float() don't like that. int()float()不喜欢那样。

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: 您可以rstrip尾随空白:

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: 或更健壮的方法是使用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. cast将为花车,整数和负数的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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