3

I'm stumbling a bit why the following code

str1 = "text"
str2 = "some longer text"
if str1 in str2 == True:
    pass # do something

is not working. (I know that I can easily fix this problem by writing if str1 in str2 == True: - this is not the question!)

The question is, why is

str1 in str2 == True

returning False? I mean if the operator in is stronger than the == operator, I would have the following code

if (str1 in str2) == True:

which is actually working (as it will be evaluated to True) ... And if it is the other way round, that the == operator is stronger than the inoperator, I would expect an TypeError: argument of type 'bool' is not iterable Exception. Actually the code

if a = "" in ("" == True):

is raising such an exception. So what is Python doing here? Which operator (in vs ==) is evaluated first? And why is the result False:

a = ("" in "" == True)

and not True or an TypeError: argument of type 'bool' is not iterableException? The only way I could imagine theFalse` result is that Python is trying to execute both operators all together. But how is it working then?

Things I noticed:

  • Python2 and Python3 are both showing the same result.
  • The statement "" in "" == "" is actually returning True
  • If you have the code a = ("" in "" == True), type(a) will result in <type 'bool'>. So the result is actually a boolean - as expected - and not some kind of other object. Nevertheless print(a) results False.
quant
  • 2,184
  • 2
  • 19
  • 29
  • There is absolutely no reason to ever write `== True` (\*except for very specific circumstances). Just do `if str1 in str2:`. What you're creating there is a *chained comparison*. – deceze Nov 13 '18 at 08:10
  • @deceze I know that there is no reason to ever write `== True`. I just wanted to know what is happening when you do it nevertheless. And neither https://stackoverflow.com/questions/25753474/python-comparison-operators-chaining-grouping-left-to-right nor https://stackoverflow.com/questions/24018315/python-chained-comparison is a duplicate. As explained in my question - when these operators would be chained, then the code `str1 in str2 == True`would either equal to `str1 in (str2 == True)` or `(str1 in str2) == True` however this is not the case. – quant Nov 13 '18 at 08:16
  • 4
    Err, no, then you don't quite understand what a chain is yet. See https://stackoverflow.com/a/25753528/476 again. What you have is equivalent to `(str1 in str2) and (str2 == True)`! – deceze Nov 13 '18 at 08:19

0 Answers0