If statement returning the wrong value?
An if
statement in Python evaluates and it appears returns the non-expected value.
p = sub.Popen('md5.exe -n md5.exe',stdout=sub.PIPE,stderr=sub.PIPE)
md5, errors = p.communicate()
print md5
abc = "8D443F2E93A3F0B67F442E4F1D5A4D6D"
print abc
if md5 == abc: print 'TRUE'
else: print 'FALSE'
repr(md5)
is '8D443F2E93A3F0B67F442E4F1D5A4D6D\r\n'
开发者_Python百科.
The 2 strings are the same, but yet it evaluates and prints FALSE
.
What's happening here, and how can this be solved?
Your md5
contains trailing whitespace, which the abc
value does not have. Most command-line programs end with a line break because it can be disruptive to shell users not to. It's possible to output this to the standard error stream so as not to interfere with programs like yours, but this is often not done.
You can use the string method .strip()
to remove all whitespace from the beginning and end of a string. For example,
md5 = md5.strip()
If you were using Python 3, the same error could have be caused because the Subprocess
object's .communicate()
method returns bytes
objects, which are not be equal to any strings.
精彩评论