Python readline()返回不会转换为int或float的字符串 [英] Python readline() returns string that wont convert to int or float

查看:341
本文介绍了Python readline()返回不会转换为int或float的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Arduino SoftwareSerial库将串行数据发送到Raspberry Rx引脚.我可以成功地将Arduino串行数据发送到Raspberry,其发送的整数与字符串中的等效整数一样.

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.

问题:

我正在尝试将.readline()返回的字符串转换为float或int,但是无法这样做.

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']

如何将其转换为int或float?我只需要对数字做一些算术.我已经尝试过:

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: ''

答案

感谢提供答案的John和Padraic,我可以确认有关如何解决上述问题的更新.我更喜欢Padraic的解决方案,它稍微优雅一些​​,但两者都能起作用.我添加了以下内容:

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的解决方案,尤其是Pad的解决方案(有关更多详细信息,请参见下面的答案):

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

推荐答案

该错误是由该行末尾的\r\n引起的. int()float()不喜欢.

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()]

这篇关于Python readline()返回不会转换为int或float的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆