比较 unicode 和 str Python3

Compare unicode to str Python3

我正在从事一个项目,在该项目中我通过串行通信从 arduino 获取数据。所以我打开 ser = serial.Serial('/dev/ttyACM1', 9600) 并且一切正常。问题是我写了这段代码来检查我得到的数据何时为 0 但我无法让它工作。

while True:
            try :
                a = ser.readline()

                # i do that because the input stream is smthg like b' 16.894548\r\n'
                data = a.decode('utf-8') 

                print(a is str(str(0).encode('utf-8').decode('utf-8', "strict")))

我尝试了很多东西,比如获取sizeof,编码和解码,解码后使所有内容成为str。但仍然没有运气。 有任何想法吗?

  • Use == to compare strings, not is

  • 注意最后有换行符。 '0' != '0/r/n'.

    尝试

    a = ser.readline()
    print(a.decode().strip() == '0')