散列结果的标准输出比较(python)

2024-05-23 21:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python为一个文件创建一个散列结果。我从其他地方检索哈希结果,但是我必须使用stdout检索它,我想比较这两个结果。但是,检索到的stdout是作为列表检索的,并且在末尾有一个\n。例如,如果我打印它,它可能看起来像这样:[6d52f\n]

我知道问题是,如果我尝试将\n添加到我当前的哈希结果中,它会自动忽略\n来尝试比较这两个结果(就像我在下面的代码中所做的那样),所以我现在有点不确定如何比较这两个结果。我知道答案可能就在眼前,但如果有任何帮助,我将不胜感激。你知道吗

我的代码是:

if ("%s\n" % thishash == otherhash):
    print "they are the same"
else:
    print "they are not the same"

Tags: the答案代码列表if地方stdoutelse
3条回答

I have to retrieve it using stdout

你的意思可能是“stdin”,而不是“stdout”。你知道吗

other_hash = raw_input() # no trailing newline
if this_hash == other_hash: 
   "same"

或者可以不带参数调用other_hash.rstrip(),删除所有尾随空格。你知道吗

只需将strip应用于其他哈希:

if thishash == otherhash.strip():
    print "they are the same"
else:
    print "they are not the same"

一些补充建议:

  1. 不要使用无关紧要的括号。像Python一样。你知道吗
  2. 或许lowercasing其他哈希可能是个好主意。你知道吗

只需从stdin中删除换行符:

>>> x = ['6d52f\n']
>>> x[0].rstrip('\n')
'6d52f'

相关问题 更多 >