Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.

The 2 strings are the same, but yet it evaluates and prints FALSE.

What's happening here, and how can this be solved?

like image 516
krtek Avatar asked Mar 06 '26 17:03

krtek


1 Answers

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.

like image 88
Jeremy Avatar answered Mar 08 '26 07:03

Jeremy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!