Hello Dynamo Friends,
I want to test if the items of a list contain multiple substrings.
I want to return the item only if it contains all substrings.
But the “and” command does nothing, the code will only search for the last string, in my case “banana”.
List = IN[0]
outlist = []
for item in List:
if ("apple" and "peach" and "banana") in item:
x = item
outlist.append(x)
OUT = outlist
Ok, so i can use the all() function after making a list out of my substrings:
List = IN[0]
outlist = []
for item in List:
if all(i in item for i in ["apple","peach","banana"]):
x = item
outlist.append(x)
OUT = outlist
With list comprehension we get:
x = [item for item in List if all(i in item for i in ["apple","peach","banana"])]
4 Likes
To search for multiple strings in a list of items in Python, you can use list comprehension or a loop to iterate through the list and check if each item contains any of the target strings.
my_list = ["apple", "banana", "orange", "grape"]
search_strings = ["apple", "grape"]
result = [item for item in my_list if any(search in item for search in search_strings)]
print(result)
1 Like