简体   繁体   中英

Python - Print out only once if string do not match a string

So I am trying to make a comparing script where I basically make if there is matching string then print it out else just print out that it doesn't contain.

My problem right now is that whenever it contains the string it print outs only once which is good but whenever it doesn't find a matching, it prints out alot of not matched strings.

etc:

for words in stackoverflow:

   word_random = words #random meaning every loop
   #"Hello my name is Python and the World is so amazing What"
   #My name is Python and it is amazing!



    Matching_keyword = ['Hello', 'World', 'What']

    for keyword in Matching_keyword:
         if keyword in word_random:
            print(keyword)

         else:
             print(keyword)

    Output:

    Hello
    World
    What
    Hello
    World
    What
    Hello
    World
    What
    Hello
    World
    What
    Hello
    World
    What
    Hello
    World
    What
    Hello
    World
    What
    Hello
    World
    ....
    ....
    ....

The output almost never ends and is alot longer than what the ouput is printed here. As you can see I have at the top a for loop which every loop it goes through it gives a new meaning which I there after compare.

My question is how can I make it so whenever it hits the true it should only print out the keyword once and same goes to the else statement?

I tried to use break but that kills the Matching_keyword loop and prints out only Hello but alot of times

for keyword in Matching_keyword:
    if keyword in word_random:
       print("Found matching" + keyword)
       break
    else:
       print("Did not find matching")
       break

This is a case where you want to use else with the loop , not the conditional.

for keyword in Matching_keyword:
    if keyword in word_random:
       print("Found matching" + keyword)
       break
else:
    print("Did not find matching")

An else clause on a loop only executes if the loop terminates because you've exhausted the iterator. If you exit with break or an exception instead, the else does not execute. So here, as soon as you find a match, you use break to stop checking other keywords, and you also avoid the else . If you never find a match, the loop terminates "naturally" (and without producing any output), and the else clause prints the failure message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM