Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python cant check for more than one matching string

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

match
match
no match
no match

Why doesn’t this work?

>Solution :

"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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading