There are two things to consider here:
How and
works with strings
'x' and 'y'
is not True
.
'x' and 'y'
is 'y'
, which might seem confusing but it makes sense when looking at how and
and or
work in general:
a and b
returns b
if a is True
, else returns a
.
a or b
returns a
if a is True
, else returns b
.
Thus:
'x' and 'y'
is 'y'
'x' or 'y'
is 'x'
What the parentheses do
The brackets do have an effect in your if statement. in
has a higher precedence than and
meaning that if you write
if 'x' and 'y' in target:
it implicitly means the same as
if 'x' and ('y' in target):
which will only check if y is in the target string. So, using
if ('x' and 'y') in target:
will have an effect. You can see the whole table of operator precedences in the Python docs about Expressions.
Solution
To achieve what you are wanting to do, @Prem and @Olga have already given two good solutions:
if 'y' in target and 'x' in target:
or
if all(c in target for c in ['x','y']):