willerson
willerson

Reputation: 79

Searching a list for certain strings in array

What I'm doing is loading a list of URLs from a .txt file which is working as it should:

def load_urls():
    try:
        input_file = open("filters\\inputLinks.txt", "r")
        for each_line in input_file:
            link = each_line.rstrip('\n')
            identify_platform(link)
    except Exception as e: 
        print("Loading URLs error: ", e)

def identify_platform(link):
    try:
        SEARCH_FOR = ["/node/", "/itemlist/"]
        if any(found in link for found in SEARCH_FOR):
            print(link)
    except Exception as e: 
        print("Identifying URLs error: ", e)

if __name__ == "__main__":
    load_urls()

It will then check if a URL contains one of the SEARCH_FOR array elements. If it does, we print it to screen. Is it possible to also print out which one of the array elements it found using something like:

print(element_found + "|" + link)

Upvotes: 0

Views: 112

Answers (2)

AirSquid
AirSquid

Reputation: 11938

Instead of using the any operator, just do a list comprehension. Note this might give you 2 results if both of the search items are in the target.

matches = [(item, link) for item in SEARCH_FOR if item in link]
for match in matches:
    print(match[0] + '|' + match[1])

Upvotes: 1

Austin
Austin

Reputation: 26037

It is possible if your separate into multiple lines, making it more readable:

for found in SEARCH_FOR:
    if found in link:
        print(found + '|' + link)

Upvotes: 2

Related Questions