Home > Software engineering >  python cant check for more than one matching string
python cant check for more than one matching string

Time:04-14

I want to check for a string match with an if statement. My code looks like this:

labels = {"Channel 1": "", "Channel 2": "", "Channel 3": "", "Channel 4": ""}
for label in labels.keys():         
       if "Channel 1" or "Channel 2" == label:
            print("match")
       else:
            print("no match")

output:

match
match
match
match

I expect to get:

match
match
no match
no match

Why doesn't this work?

CodePudding user response:

"Channel 1" or "Channel 2" == label will evaluate to True because "Channel 1" as a string with content will always evaluate to True.

The order of operations here looks like this: ("Channel 1") or ("Channel 2" == label)

What you want to do is one of these

if label == "Channel 1" or label == "Channel 2":
    pass
if label in ("Channel 1", "Channel 2"):
    pass

CodePudding user response:

Problem is with this line:

if "Channel 1" or "Channel 2" == label:

Basically you are trying to check if "Channel 1" exists OR "Channel 2" equals label.

What you probably want instead is this:

if "Channel 1" == label or "Channel 2" == label:
  • Related