I'm confused [because] the if statement should result in False since 'jpg' is in the text. It should give me True only when none of them is in the text. Correct ?
No, the or
operator is True
if one or both of the operands is True
. So from the moment, 'jpg'
is not in the text, or 'png'
is not in the text, or jpeg
is not in the text, the test succeeds.
What you want here is the and
operator. x and y
is True, only when both operands (x
and y
) are not in the text. So we can use:
if 'png' not in text and 'jpg' not in text and 'jpeg' not in text:
print('True')
else:
print('False')
Since it can be confusing, and since this is a long expression, we can also use the all(..)
builtin function here:
if all(part not in s for part in ['png', 'jpg', 'jpeg']):
print('True')
else:
print('False')
So only if all these part
s are not in s
, then the condition succeeds.