简体   繁体   English

如何比较两个都在python中包含字符串的变量?

[英]How do I compare two variables which both contain strings in python?

I'm making a account login system in python by having the username and password stored in a separate file and the program access it, then read the password and compare it with what the user has entered. 我正在用python创建一个帐户登录系统,方法是将用户名和密码存储在一个单独的文件中,然后程序访问它,然后读取密码并将其与用户输入的内容进行比较。 It can read the password in the file but for some reason when it compares it to what the user has entered, it always says it's wrong. 它可以读取文件中的密码,但是由于某种原因,将其与用户输入的内容进行比较时,它总是说错了。

I've tried comparing the actual password to the user's input and I know it's reading the file right as I made it print out what it read and it printed the correct password. 我已经尝试将实际密码与用户输入进行比较,并且我知道它正在正确读取文件,因为我已将其打印出来并打印了正确的密码。 I've also made it print the user's input to make sure that's right and that was working too. 我还使其打印了用户的输入,以确保这是正确的并且也可以正常工作。

Just so you know, the file already exists which contains the password on the second line and it finds the right file as the file is named after the account that it's for. 可以知道,该文件已经存在,在第二行包含密码,它会找到正确的文件,因为该文件是根据其使用的帐户命名的。

Account = str(input("Enter the username. "))
Account_Password = str(input("Enter the password. "))
AccountFileName = (Account + ".txt")
with open(AccountFileName,"r") as AF:
    for x, line in enumerate(AF):
        if x == 1:
            Account_Password_Check = (line)
if Account_Password == Account_Password_Check:
    print("Welcome, " + Account + "!")
else:
    print("Either the username or password were incorrect.")

If the user input is the same as the password, it should print, "Welcome (username here)!" 如果用户输入的密码与密码相同,则应显示“欢迎使用(此处为用户名)!”。 and if they're different then it should print, "Either the username or password were incorrect." 如果它们不同,则应打印“用户名或密码不正确”。

If you know what's wrong, please let me know. 如果您知道出了什么问题,请告诉我。

Thanks. 谢谢。

In comments to your question, you will find the first reason why it doesn't work, but: 在对问题的评论中,您会找到它不起作用的第一个原因,但:

for x, line in enumerate(AF):
        if x == 1:
            Account_Password_Check = (line)

Is also not fully correct, enumerate start count from zero, but condition checks 1 line, it means that you will compare your current user password from previous. 也不完全正确,从零开始enumerate ,但条件检查1行,这意味着您将比较以前的当前用户密码。 The correct version will be 正确的版本将是

for x, line in enumerate(AF):
        if x == 0:
            Account_Password_Check = line.strip()
            break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM