如何将byteclass对象转换成字符串对象

How to convert the byte class object into a string object

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') 但其中 none 正在运行。我的 python 版本是 3.4.3.

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

I tried ardstr = str(ardstr).strip('\r\n') and ardstr.decode('UTF-8')

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

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

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

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

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