为什么我的两个python字符串在程序中不相等但在解释器中相等?[重复]
这个问题已经在这里有了答案 :
2个相同的字符串“不相等” [Python] (1个答案)
Python两个相同的字符串被视为不同 (1个答案)
去年关闭。
我正在尝试使用python编写聊天服务器。我正在使用SHA1哈希来验证用户,并将用户存储的哈希与给定密码的哈希进行比较,如果它们相同,则应该验证用户。
我的哈希函数如下所示:
def sha1_encode(string):
import hashlib
return hashlib.sha1(bytes(string)).hexdigest()
我的验证用户如下所示:
def validate_user(self, user, password):
if user in self.users:
print "user exists"
#Get the saved SHA1 hash and see if it matches the hash of the given
#password
print "sha", sha1_encode(password)
print "stored", self.users[user]
print "equal", self.users[user] == sha1_encode(password)
print type(self.users[user])
print type(sha1_encode(password))
if str(self.users[user]) == str(sha1_encode(password)):
print "validate loop entered"
return True
else:
return False
当我与一个我知道在列表中的用户一起运行时,得到以下输出:
user exists
sha 61503cfe0803f3a3b964b46a405f7828fd72b1f7
stored 61503cfe0803f3a3b964b46a405f7828fd72b1f7
equal False
<type 'str'>
<type 'str'>
所以我知道它们都是字符串,而且我知道它们都是同一件事,但出于某种原因返回false。我最初是在质疑不同类型的对象,但事实并非如此。
因此,我尝试将这些字符串复制到解释器中,并检查它们是否实际上相等:
In [1]: x = '61503cfe0803f3a3b964b46a405f7828fd72b1f7'
In [2]: y = '61503cfe0803f3a3b964b46a405f7828fd72b1f7'
In [3]: x == y
Out[3]: True
在这一点上,我感到困惑,为什么它在函数中没有报告true,而在解释器中却没有报告true,特别是因为似乎我只是用不同的变量名在做同样的事情。谁能告诉我发生了什么事?任何帮助将不胜感激。