What is the logic of == and in comparison?

Viewed 32

So I was looking for questions and came across this recent question

The answer for it is very simple but the one thing I noticed is that it actually did return SPAM for exact match

So this snippet of code

text = 'buy now'

print(text == 'buy now' in text)  # True

returns True and I don't get why

I tried to figure out by placing brackets in different places and

text = 'buy now'

print(text == ('buy now' in text))  # False

returns False and

text = 'buy now'

print((text == 'buy now') in text) # TypeError

raises TypeError: 'in <string>' requires string as left operand, not bool

My question is what is happening right here and why is it like that?

P.S.

I am running Python 3.8.10 on Ubuntu 20.04

1 Answers

Both == and in are considered comparison operators, so the expression text == 'buy now' in text is subject to comparison chaining, making it equivalent to

text == 'buy now' and 'buy now' in text

Both are operands of and are True, hence the True result.

When you add parentheses, you are either checking if text == True (which is False) or if True in text (which is a TypeError; str.__contains__ doesn't accept a Boolean argument).

Related