Prutser Prutser - 1 month ago 4
Python Question

Python: Comparing strings in a list with two different list lengths

I have two lists containing strings with different lengths.
Now I want to check if a string in one list is the substring of the other list
to create a newlist with the same length as the string_list.

string_list = ['expensive phone', 'big house', 'shiny key', 'wooden door']
substring_list = ['phone','door']


What I have done so far

newlist=[]
for i in string_list:
for j in substring_list:
if i in j:
newlist.append(j)
print newlist


So it gives me

newlist = ['phone', 'door']


But what I am trying to achieve is a list as following

newlist = ['phone', '-', '-', 'door']

Answer

for loops can take an else block. You can use this else block to append the '-' in the case where the string is not found:

newlist=[]
for i in string_list:
    for j in substring_list:
        if j in i:
            newlist.append(j)
            break
    else:
        newlist.append('-')
print(newlist)
# ['phone', '-', '-', 'door']

If you want the result to be same length as the first list, you need to put a break in the if so that if the two items are contained in one of the strings (e.g. 'expensive phone door'), you won't make two appends which will skew the resulting list length.

The break also ensures the else block of the for is not executed when an item has been found.

Comments