问题描述
我正在使用 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.
你可以像这样剥掉它:
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 的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!