0

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"

blhsing
  • 91,368
  • 6
  • 71
  • 106
Anders_K
  • 982
  • 9
  • 28
  • 1
    voted to reopen as [the duplicate](https://stackoverflow.com/questions/15851146/checking-multiple-values-for-a-variable) offers no explanation why this does not work. – hiro protagonist Mar 11 '19 at 13:43

1 Answers1

4
  • "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 sets you could also try this:

if set("az") & set(x):
    ...
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111