1

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

sudden_appearance
  • 1,968
  • 1
  • 4
  • 15
  • in is a keyword used to either iterating objects or items in a list, or in conditional functions. print(text == 'buy now' in text) This returns True bc 'buy now' is indeed in text. Its kinda like an if. – Josip Juros Mar 04 '22 at 13:01

1 Answers1

5

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

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Wow, that seems really strange in that context. I knew chains work with `==, !=, >, <, >=, <=`. Didn't know that it works with `in` also) Thanks for answer – sudden_appearance Mar 04 '22 at 13:07
  • Yeah, I can see the argument for `in` (and `is`, and their negative companions) to be comparison operators, but I've never really thought it useful to include them in chaining. – chepner Mar 04 '22 at 13:08