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 in
operator, 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 the
False` 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 returningTrue
- 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. Neverthelessprint(a)
resultsFalse
.