Python (pySerial) : cannot trim/remove CR, LF 或字符串中的意外字符

标签 python string pyserial

我正在使用 Arduino 从传感器输出温度和湿度数据,这是由运行 Python 使用 pySerial 的 PC 读取的。数据读入正确,但我想删除 CR/LF 和意外字符。我在此站点上发现的一个想法是使用 lstrip 或 lreplace,但它们似乎无法正常工作。他们将删除该字符的一个实例,但即使重复该行或制作一个小循环也没有任何效果。

这是程序打印的内容(在我尝试删除不必要的字符后,底行是字符串):

[b'\n', b'\r\n', b'Read sensor: OK\r\n', b'Hum40.00\r\n', b'TempC18.00\r\n']

[" b'Hum40.00\r\n'", " b'TempC18.00\r\n']"]

我的目标是阅读:

[Hum40.00, TempC18.00]

我希望稍后可以微调消息。

这是代码:

    import serial as ser
    import time

    count = 0
    msgArray = []
    saveMsg = []

    ser = ser.Serial('COM16', 9600, timeout=1, parity='N', stopbits=1,                                bytesize=8, xonxoff=0) # Setting up and opening COM port
    ser.close()
    ser.open()

    def readSerial():               #reads a whole line from COM port
        serLine = ser.readline()
        return serLine

    def sveMsgCut():                #saves the buffer as a message then cuts message
        cutMsg = saveMsg
        words = cutMsg.split(',')
        return words

    while True:                     #main program
        dataSerial = readSerial()

        if count < 5:                       #reads COM port 5 times and passes along to buffer msgArray
            msgArray.append(dataSerial)
            count = count+1
        else:
            print(msgArray)                     #~display msgArray
            saveMsg = str(msgArray)             #convert to string
            splitMsg = saveMsg.split(',')       #splits string (csv)
            phrase = splitMsg[3:5]              #cuts out excess either side of Temp & Hum/
            phraseString = str(phrase)
            phraseNew = phraseString.lstrip("/n") #an attempts ot remove CR

            print(phraseNew)                    #~print adjusted string

            saveMsg = msgArray
            count = 0       #resets msgArray and counter
            msgArray = []



            time.sleep(5)

我是编程新手,尤其是 Python,所以它可能是我错过的一些简单的东西,但尝试了几种不同的想法并且无法删除多余的字符。

最佳答案

不确定为什么 rstrip/lstrip 不适合你。

此代码在我的机器上按预期运行:

s = '\r\nHum40.00\r\n'
print (s.rstrip().lstrip())

我看到的唯一区别是“/n”参数,所以请尝试:

phraseNew = phraseString.lstrip()

关于Python (pySerial) : cannot trim/remove CR, LF 或字符串中的意外字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36543649/

相关文章:

java - 对象的堆与字符串常量池内存表示

Heroku 上的 Python 和 Node.js

Python 目录 hell

python - 如何使用 Scrapy 在页面内进行爬取?

python - 将随机值设置为字典的一半并复制其余部分

php - 插入MYSQL字符串、PHP时POST值变空

java - 从 char 到 int : why (int)givenString. 的转换 charAt(2) 给出 48 with givenString = "11001"?

python - python 中的 usb 自动检测 for linux env

python - pySerial inWaiting 返回不正确的字节数

pyserial - twisted.internet.serialport 17.1.0 可以在 Windows 上运行吗?