【问题标题】:invalid literal for int() with base 10: '328.94'(while converting bytes to int())基数为 10 的 int() 的无效文字:'328.94'(将字节转换为 int() 时)
【发布时间】:2020-08-08 05:24:22
【问题描述】:

这是我的代码:

import serial

print('Arduino is setting up')
# Setting up the Arduino board

arduinoSerialData = serial.Serial('com4', 9600)
while True:
    if arduinoSerialData.inWaiting() > 1:
        myData = arduinoSerialData.readline()
        myData = str(myData)
        myData = myData.replace("b'", '')
        myData = myData.replace("\\r\\n'", '')
        myData1=myData
        if myData1.find("a"):
            myData1= myData1.replace("a",str(0))
            if int(myData1)<100:
                print(myData)

此代码的作用是从连接到 arduino 板上的超声波传感器导入数据并打印出来。myData 最初以字节为单位,所以我将其转换为字符串,但我似乎无法将其转换为 @ 987654323@.当我尝试上面的代码时,我得到尝试这个代码,我得到这个错误。有人知道如何解决这个问题吗?谢谢!

【问题讨论】:

  • 改用float()
  • 哇,这出乎意料的效果,但是有没有合适的方法可以将它转换为浮动?我尝试了在线给出的方法,但它们没有用
  • 你没有告诉我们返回的数据格式是什么,如果不是你自己写的,你必须检查你使用的硬件/代码的文档。如果该值是一个浮点数,并且看起来是作为字符串返回的,那么这是正确的方法。

标签: python python-3.x serial-port byte arduino-uno


【解决方案1】:

您的字节到字符串的转换似乎不正确。为什么不试试这个:

1. Bytes to string conversion:
   mydata  = myData.decode("utf-8")

2. Eliminatinf trailing newline characters:
   myData = myData.strip("\r\n")

确保生成的字符串仅包含要转换为 int 的数字字符。你可以做这个检查:

if mydata1.isdigit() and int(mydata1) < 100:
    <your code>

如果你的字符串包含浮点数,那么你可以这样做:

if mydata1.replace(".", "").isdigit() and int(float(mydata1)) < 100:

【讨论】:

    【解决方案2】:

    如果你给int()一个字符串,它必须是一个整数。如果您有一个非整数,则可以先使用float() 将其转换,然后使用int() 将该浮点值转换为整数,如下所示:

    >>> print(int("328.94"))               # Will not work.
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: '328.94'
    
    >>> print(float("328.94"))             # Convert string to float.
    328.94
    
    >>> print(int(float("328.94")))        # Convert string to float to int.
    328
    
    >>> print(int(float("328.94") + 0.5))  # Same but rounded.
    329
    

    如果您希望将其舍入到最接近的整数而不是截断,则最后一个是一个选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 2013-05-31
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2019-06-15
      • 2015-11-05
      相关资源
      最近更新 更多