Anders_K
Anders_K

Reputation: 992

Python substring in string

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

Answers (1)

hiro protagonist
hiro protagonist

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

if set("az") & set(x):
    ...

Upvotes: 4

Related Questions