简体   繁体   中英

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.

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. any suggestion as on how to overcome this behavior?

Output i got is:

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.

In your case you are missing the any :

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

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