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")
>Solution :
You should instead use any:
if any(animal in str_a for animal in animals):
print('T')
else:
print('F'