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']
for i in string_list:
for j in substring_list:
if i in j:
newlist = ['phone', 'door']
newlist = ['phone', '-', '-', 'door']
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.
break also ensures the
else block of the
for is not executed when an item has been found.