【问题标题】:How to convert the byte class object into a string object如何将字节类对象转换为字符串对象
【发布时间】:2018-12-08 20:25:09
【问题描述】:
import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *

data = serial.Serial('com3',115200)
while True:
    while (data.inWaiting() == 0):
    pass
ardstr = data.readline()
print (ardstr)

我在这里尝试从 arduino 获取数据,但它的格式为 b'29.20\r\n'。我想要"29.20" 格式的数据,以便绘制它。

我试过ardstr = str(ardstr).strip('\r\n')ardstr.decode('UTF-8') 但他们都没有工作。我的python版本是3.4.3。

我该怎么做才能得到"29.40"而不是"b'29.20\r\n'"的结果?

【问题讨论】:

  • ardstr = data.readline().decode('utf8').rstrip() 不会给您想要的结果? (或者根据您的其他计划在打印时执行此操作)。

标签: python python-3.x matplotlib arduino-uno


【解决方案1】:

如果你想在一行中完成,你可以尝试:

ardstr = ardstr.decode('UTF-8').rstrip()

rstrip() 将返回删除尾随字符的字符串副本。

【讨论】:

    【解决方案2】:

    我试过ardstr = str(ardstr).strip('\r\n')ardstr.decode('UTF-8')

    你很接近!与.strip() 调用一样,使用.decode() 方法返回新值。

    ardstr = ardstr.strip()
    ardstr = ardstr.decode('UTF-8')
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 2018-09-12
      • 2017-02-07
      • 2018-07-19
      • 1970-01-01
      • 2021-02-23
      • 2023-01-13
      • 2015-08-10
      相关资源
      最近更新 更多