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

How to use set.intersection in an if-statement?

I want to check if multiple strings are within a larger string called "str_a". The following is what I currently have and it works.

animals = {"giraffe", "tiger"}
str_a = "A giraffe is taller than a tiger."

if "giraffe" in str_a or "tiger" in f:
    print ("T")
else:
    print ("F")

However, I wanted to represent the if-statement in a more concise manner and I think set.intersection can help me achieve that. I tried the following with set.intersection and it prints out "F" instead of "T" – I’m not sure why. Any guidance on this would be appreciated!

animals = {"giraffe", "tiger"}
str_a = "A giraffe is taller than a tiger."
matches = animals.intersection(str_a)

if matches:
    print ("T")
else:
    print ("F")

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

>Solution :

You should instead use any:

if any(animal in str_a for animal in animals):
    print('T')
else:
    print('F'
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