Skip to content Skip to sidebar Skip to footer

How To Compare Lists Of Words And Strings, Then To Print Full String That Contains Word Using Python?

Compare 2 lists in python. First list contain words and second list with strings/lines. If any word in list1 is found in list2 (strings), then print full matched string/lines. list

Solution 1:

To check every element in list2 you have to loop over every element of that list. For each of those elements you have to check if it is a part of any element in list1.

for line in list2:
    if any(value in line for value in list1):
        print(line)

Solution 2:

If you want to check if a string i contains string j, you can do it using i in j. Then comes the part how do you want the output actually. What my approach was to go through the list1 and for each of them go though the list2 and check if element of list2 contains the element of list1. If contains then i checked if they are equal or not. If equal i skipped them. Otherwise i have printed the element of list2.

As @mathius indicated, my code will print the same element of list2 more than once. I didn't handle that because to me, post maker didn't want that. Look forward to your opinion. Here is my code:

for i in list1:
    for j in list2:
        if i in j and i != j:
            print j

Post a Comment for "How To Compare Lists Of Words And Strings, Then To Print Full String That Contains Word Using Python?"