Python-如果字符串与字符串不匹配,则仅打印一次

时间:2018-11-17 13:48:40

标签: python loops if-statement compare

因此,我尝试制作一个比较脚本,基本上在该脚本中,如果有匹配的字符串,则将其打印出来,否则只打印其中不包含的字符串。

我现在的问题是,每当包含字符串时,它只打印一次,这很好,但是每当找不到匹配项时,它就会打印出很多不匹配的字符串。

等:

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
    ....
    ....
    ....

输出几乎永远不会结束,并且比输出的输出长很多。如您所见,我在顶部有一个for循环,它经过的每个循环都赋予了新的含义,在比较之后,我就知道了。

我的问题是如何做到这一点,以便每当它击中 true 时,它只应打印一次关键字,并且在 else 语句中输入相同的内容?

我尝试使用break,但是这杀死了Matching_keyword循环,只打印了Hello,但打印了很多次

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

1 个答案:

答案 0 :(得分:1)

在这种情况下,您想将else循环一起使用,而不是有条件的。

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

循环上的else子句仅在循环终止时才执行,因为您已经用尽了迭代器。如果退出时返回break或一个异常,则else不会执行。因此,在这里,一旦找到匹配项,就使用break停止检查其他关键字,同时也避免使用else。如果您从未找到匹配项,则循环“自然地”终止(并且不产生任何输出),并且else子句显示失败消息。

相关问题