Home > Net >  Python parentheses seem to be changing equality evaluation
Python parentheses seem to be changing equality evaluation

Time:05-26

I'm comparing two strings and was banging my head against the wall for an hour trying to figure out why they weren't equal. Turns out I needed parentheses to clarify what was being evaluated. Could someone explain what's happening here?

This code:

print("Line 1 equal=%s" % actual_line1 == expected_line1)

Evaluates to:

False


This code:

print("Line 1 equal=%s" % (actual_line1 == expected_line1))

Evaluates to:

Line 1 equal=True

CodePudding user response:

The first one is equivalent to

print(("Line 1 equal=%s" % actual_line1) == expected_line1)

because of operator precedence. According to a relevant python doc, % has higher precedence than == (look at the table therein as well as footnote 6).

Nowadays it is recommended to use an f-string, which is more readable:

print(f"Line 1 equal={actual_line1 == expected_line1}")

CodePudding user response:

This is because

print("Line 1 equal=%s" % actual_line1 == expected_line1)

is the same as

 print(("Line 1 equal=%s" % actual_line1) == expected_line1)

Instead of

print("Line 1 equal=%s" % (actual_line1 == expected_line1))

which is what you wanted. More info

  • Related