简体   繁体   English

elif 条件无法正常用于 python 中的字符串匹配

[英]elif condition not working properly for string matching in python

I am developing a webscraping code, while doing so i am trying to modify the code as to extract specific element if the website link has a string from the predefined list of strings.我正在开发一个网页抓取代码,同时我正在尝试修改代码以在网站链接具有来自预定义字符串列表的字符串时提取特定元素。 I am trying to do this with the help of if elif condition.我试图在 if elif 条件的帮助下做到这一点。

the context is something similar to this:上下文与此类似:

list1 = ["apple","bat"]
list2 = ["cat", "mat"]

tester = ["www.cat.com","www.website.com","www.apple.com"]
for a in tester:
    print(a)
    if (item1 in a for item1 in list1):
        print("apple is present")
    elif ("john" in a):
        print("failed")
    elif (item2 in a for item2 in list2):
        print("cat is present")

but the problem is the match is not happening properly, the loop is giving the output of the first condition, not going to the second check condition.但问题是匹配没有正确发生,循环给出了第一个条件的 output,而不是第二个检查条件。 any suggestion as on how to overcome this behavior?关于如何克服这种行为的任何建议?

Output i got is:我得到的 Output 是:

apple is present
apple is present
apple is present

If the if is always succeeding rather than the elif, then the problem is that if itself, not the elif.如果 if 总是成功而不是 elif,那么问题在于 if 本身,而不是 elif。

In your case you are missing the any :在您的情况下,您缺少any

if any(item1 in a for item1 in list1):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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