簡體   English   中英

Python readline()返回不會轉換為int或float的字符串

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

我正在使用Arduino SoftwareSerial庫將串行數據發送到Raspberry Rx引腳。 我可以成功地將Arduino串行數據發送到Raspberry,使我發送的整數與字符串中的等效整數一樣多。

問題:

我正在嘗試將.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']

如何將其轉換為int或float? 我只需要對數字做一些算術。 我努力了:

    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的解決方案,雖然稍微優雅一些​​,但兩者都能起作用。 我添加了以下內容:

John的解決方案,尤其是Pad的解決方案(請參見下面的答案以獲取更多,更多的信息):

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

該錯誤是由行尾\\r\\n引起的。 int()float()不喜歡那樣。

您可以像這樣將其剝離:

sInput = oSer.readline().strip()

或者,您可以修改循環以忽略非數字:

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

您可以rstrip尾隨空白:

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

或更健壯的方法是使用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將為花車,整數和負數的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM