首页 > 解决方案 > 在文本框中搜索 str 的模块接受任何匹配

问题描述

以下是搜索文本框的代码,将 4 个字符分隔到各自的变量中并检查变量是否匹配,但错误出现在“If str(user_text) == str(B):”行中(第 17 行) . 尽管它应该是,但它永远不是真的,如果 == 更改为“in”,它允许任何数量的匹配,这对于我正在设计的应用程序是不安全的,因为它允许任何人访问该帐户。有什么办法可以帮助解决这个问题??

def Check(user_text):
    global count,  s
    #while looking for line
    fh =open("user_info.txt", "r")
    found = False
    while found == False :
        print("Here")
        s =fh.readline()
        print(s)
        #seperate the words
        if s != "":
                
            N,M,A,B=s.split("~")
            print(f"B ={B}")

            #if its found
            if str(user_text) is str(B):
                found = True
                print ("line Number:", count, ":", s)
                print(found)
                return found
        count+=1
        print(found)
        if count >40:
            return found
    fh.close()

测试数据包括:Lol~Nope~JP~232323 John Smith~NOPE~Nope~76231 它应该只检查最后一个变量。

谢谢

标签: pythonpython-3.x

解决方案


问题是,当您readline()在读取文件行时使用函数时,它会\n在字符串的末尾添加一个(检查参考),所以正如您所提到的,您永远不会found成为True.

一个简单的解决方案可能是\n像这样用空白替换:

N,M,A,B=s.replace("\n", "").split("~")

推荐阅读