我正在阅读串行数据,这是Python词典的关键。当我读取串行数据时,它作为字节流传递,我将其转换为字符串。当我使用该字符串搜索字典Key时,我得到一个KeyError。
我试图通过手动输入密钥来搜索相同的密钥,这将完全返回值。我的代码如下,任何帮助表示赞赏!
plates_id = {'TestCylinder100umHard': 8, 'TestCube100umHard': 7, 'MotorMount100umHard': 6, 'InnerShaft100umHard': 5, 'DriveSleeve100umHard': 4, 'DrivePulley100umHard': 3, 'BearingSleeve100umHard': 2, 'Quad': 1, 'Auto Calibration Plate': 0}
s_bytes_new = ser.inWaiting()
s_new = str(ser.read(s_bytes_new))
printing_plate = plates_id[s_new]
print(printing_plate)
出现此错误:
Traceback (most recent call last):
File "C:/pythonProjects/nanoDLP/touchInterface/printTest.py", line 66, in <module>
printing_plate = plates_id[s_new]
KeyError: "'Auto Calibration Plate'"
如果您需要更多信息,请与我们联系。谢谢,
迪伦
答案 0 :(得分:0)
使用.decode()而不是str,将字节转换为str
s_new = ser.read(s_bytes_new).decode()