The real question is what str1 and str2
evaluates to, or actually what 'a' and 'b'
evaluates to. It turns out that 'a' and 'b'
evaluates to 'b'
.
Therefore in your example, str1 and str2 and str3
evaluates to Goodbye.
which explains why len(str1 and str2 and str3)
is 8.
Interestingly enough, while 'a' and 'b'
is 'b'
, 'a' or 'b'
is 'a'
.
Why?
I believe it has to do with Short-circuit evaluation.
Since bool('a')
(or any non-empty string) is True, the Python interpreter needs to evaluate True and True
or in our second case, True or True
.
For optimization reasons explained in the Wikipedia page I linked to, when evaluating True and True
the second True
will be returned but while evaluating True or True
the first True
can be returned (because True or anything
will always be True
there is no reason to bother evaluating the second term).
In order to get your desired result you should use the +
operator:
str1 = "Hi, how are you?"
str2 = "Fine."
str3 = "Goodbye."
print len(str1 + str2 + str3)