I want to find if a specific string is contained inside the elements of a list. If the string is found, I want to print out "String found", otherwise "String not found". But, the code I came up with, makes multiple prints of "String not found". I know the reason why, but I don't know how to fix it and print it only one of the messages once.
animals=["dog.mouse.cow","horse.tiger.monkey",
"badger.lion.chimp","trok.cat. bee"]
for i in animals :
if "cat" in i:
print("String found")
else:
print("String not found")
~
Add a break
statement in the if
block when the string is found, and move the else
to be the else
of the for loop. If this case if the string is found the loop will break and the else will never be reached, and if the loop doesn't brake the else will be reached and 'String not found'
will be printed.
for i in animals:
if 'cat' in i:
print('String found')
break
else:
print('String not found')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With