Consider the statement below:
Prob 1:
>>> a="abc"
>>> 'd' or 'e' in a
'd'
Someone please explain this . I was expecting a True or False …
Prob 2:
>>> print any(c in a for c in 'da')
True
Whats happening here ? If i do this ,
>>> (c in a for c in 'da')
<generator object <genexpr> at 0x011E4300>
As you can see , it gives generator object…What role does ‘any’ (method,function ??) play
here? And the result ?
Prob 3:
>>> Pattern="sdfdfg"
>>> if '\\'or '^' or '.' in Pattern:
print "yes"
else:print "no"
yes
How on earth is this “YES” ??
Show me the light someone plz………..
The results you are seeing are the result of the precedence of the
orandinoperators being different than you expect.'d' or 'e' in aThis should be read as
'd' or ('e' in a), that is, the 2 operands toorare'd'and('e' in a). Sincedis considered a true value in python,ordoesn’t look at its next operand, and just returns its first operand,'d'. Note that this means thatorisn’t just a logical OR, it can deal with other types, and return other types.print any(c in a for c in 'da')Read this
print any((c in a) for c in 'da'), ie, go over the elementns of'da', test if that letter is also ina, and then see if that held true for any of them. The reason you see<generator object <genexpr> at 0x011E4300>is that Python does not show you the elements of a generator unless it has cause to step over them. If you want to see the individual elements, write:if '\\'or '^' or '.' in Pattern:Again, read this
if ('\\' or '^') or ('.' in Pattern:). Since'\\'is true, the result is true.Table of precedence