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"

1
  • 1
    voted to reopen as the duplicate offers no explanation why this does not work. Commented Mar 11, 2019 at 13:43

1 Answer 1

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):
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.