python readline返回什么类型_Python readline()返回不会转换为int或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()]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值