I know how to test multiple boolean conditions (as below), but am wondering if I can combine testing multiple boolean conditions by grouping variables together, as below? Is there a way to shorten the working, but complex, compound boolean condition (version 1) in a comprehensible manner?
(In my real code, the actual test strings would vary at runtime, and would be variables).
Example:
AnimalString = 'We were looking for a mouse in our house.'
s = AnimalString
# 1) WORKS if-statement, but very long.
if 'dolphin' in s or 'mouse' in s or 'cow' in s:
print('1: At least one listed animal is in the AnimalString.')
# 2) DOESN'T WORK Desired complex compound boolean expression
if ('dolphin' or 'mouse' or 'cow') in s:
print('2: At least one listed animal is in the AnimalString.')
# 3) DOESN'T WORK Desired complex compound boolean expression
if 'dolphin' or 'mouse' or 'cow' in s:
print('3: At least one listed animal is in the AnimalString.')
I know why versions 2),3) don't work based on the SO posts - here and here:
- version 2) returns a boolean expression result as
True or True or False
, which falsely prints the message. - version 3) tests only for the string
'dolphin'
in the AnimalString and gives no output.
Additional question:
Any idea, maybe, if this can be solved in an even cleaner manner? Without any()
, just tuples/lists and operators...
Accepted solution: Going through comments, answers and documentation this seems to be the best solution:
any(item in AnimalString for item in ['dolphin', 'mouse', 'cow'])