尝试在涉及RFID的python中进行简单比较无法成功比较

问题描述

我在树莓派上连接了一个RFID标签,我在RFID标签上写了一个测试字符串,字母为'ab'。

def read():
    reader = SimpleMFRC522()
    #stores id number and a 'password' (ab is stored as text)
    try:
        id,text = reader.read()
    finally:
        GPIO.cleanup()
    return text

if __name__ == '__main__':
    password = read()
    print(password)
    if password == 'ab':
        print("password: "+password)
    else:
        print("Incorrect tag.")

我跑步时得到:

ab
Incorrect tag.

我应该得到 password: ab

在我的程序中,我有一个read()函数,该函数仅返回标签“ ab”上的文本。

主要,我将分配给read()的变量与字符串'ab'进行比较,它应该只打印

password: ab 相反,它被视为不正确,并转到else语句。

有人知道这可能是什么吗?

我所做的事情:

  • 我尝试通过将str()包裹在密码和'ab'上来强制将它们作为字符串,即使它们已经是字符串了。

  • 我已经检查了密码类型。这是一个字符串。

    print(type(password))
    

我也将声明更改为

if True:

仅查看是否可以执行print语句。是的。

考虑到我读取的标签中没有空格,我不确定该错误将是什么,它实际上只是字母'ab'

解决方法

您必须使用 strip() 函数。

if(password.strip() == "ab"): 它必须工作。