Print the message only once from the for loop

I want to find if a specific string is contained inside list items. If a string is found, I want to print "String found", otherwise "String not found". But, the code I came up with makes a few prints of "String not found". I know the reason, but I do not know how to fix it and print only one of the messages.

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") 

~

+4
source share
4 answers

Add a break line to the if block when the line is found, and move the else to the else of the for loop. If this case, if a string is found, the loop will break, and else will never be reached, and if the loop does not stop, another 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') 
+6
source

There is a shorter way to do this in one line. :)

 >>> animals=["dog.mouse.cow","horse.tiger.monkey","badger.lion.chimp","trok.cat. bee"] >>> print "Found" if any(["cat" in x for x in animals]) else "Not found" Found >>> animals = ["foo", "bar"] >>> print "Found" if any(["cat" in x for x in animals]) else "Not found" Not found 

It depends on the fact that the sum will return 0 if each element in the list is False, and otherwise it will return a positive number (True).

+3
source

any returns True if bool(x) is True for any x in the iterable passed to it. In this case, the expression for the generator is "cat" in a for a in animals . What a check if "cat" contained in any of the elements inside the animals list. The advantage of this method is that in all cases it is not necessary to go through the entire list.

 if any("cat" in a for a in animals): print "String found" else: print "String not found" 
+2
source

You can also use next () :

 next(("String found" for animal in animals if "cat" in animal), "String not found") 

DEMO:

 >>> animals=["dog.mouse.cow","horse.tiger.monkey","badger.lion.chimp","trok.cat. bee"] >>> next(("String found" for animal in animals if "cat" in animal), "String not found") 'String found' >>> animals=["dog.mouse.cow","horse.tiger.monkey"] >>> next(("String found" for animal in animals if "cat" in animal), "String not found") 'String not found' 
+1
source

Source: https://habr.com/ru/post/1501839/


All Articles