Reputation: 992
Suppose this code
x = "boo"
if "a" or "z" in x:
print(True)
else:
print(False)
returns True.
But why?
I expected it to return False, becuause neither a nor z is in x.
Do I misunderstand in
?
I frequently use in
to see if a string contains a single substring. E.g.
x = "eggs and spam"
if "spam" in x:
return "add sausage"
Upvotes: 0
Views: 189
Reputation: 46849
"a" or "z" in x
is evaluated as "a" or ("z" in x)
(see operator precedence to understand why) "z" in x
is False
for x = "boo"
"a" or False
is True
(as "a"
is a non-empty string; bool("a") = True
).what you mean to do is this:
if "a" in x or "z" in x:
...
if you are comfortable working with set
s you could also try this:
if set("az") & set(x):
...
Upvotes: 4