【问题标题】:Python won't accept two same strings as the samePython不会接受两个相同的字符串
【发布时间】:2017-09-06 14:14:54
【问题描述】:

我是 Python 的新手,我陷入了以下情况:

我想对密码进行哈希处理并将其与 masterhash 进行比较。不幸的是,Python 不接受它们是一样的:

import hashlib
h=hashlib.sha512()
username='admin'
username=username.encode('utf-8')
h.update(username)
hexdigest=h.hexdigest()
hlist=open("database.txt")#masterhash
lines=hlist.readlines()
userhash=lines[0]#masterhash in line 0
if userhash == hexdigest: # it doesent accept them as the same
        text = "True"
else:
        text="False"

我已经检查了对象类型:两个字符串

哈希,两次:

c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9077ec

我真的不明白这个问题。

【问题讨论】:

  • 是的 c7ad44cbad762a5da0a452f9e854fdc1e0e7a52a38015f23f3eab1d80b931dd472634dfac71cd34ebc35d16ab7fb8a90c81f975113d6c7538dc69dd8de9span>

标签: python string python-3.x comparison string-comparison


【解决方案1】:

问题出在这一行:

lines = hlist.readlines()

此列表中的每个值都有一个尾随换行符(printing 时您可能不会注意到)。确保你 strip 关闭。

userhash = lines[0].strip()

【讨论】:

    【解决方案2】:

    readlines() 返回末尾带有换行符的行。您正在将“A”与“A\n”进行比较。试试这个:

    if userhash.strip() == hexdigest
    

    【讨论】:

      【解决方案3】:

      当您使用readlines() 时,您会得到一个在每行末尾带有换行符的行列表,您可以执行以下两个选项之一:

      选项 #1:

      lines = hlist.readlines()
      userhash = lines[0].rstrip()
      

      选项 #2:

      lines = hlist.read().splitlines()
      userhash = lines[0]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-03
        • 2015-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多