I have a string and a list:
my_string = "one two three"
my_list = ["one", "two", "three", "four"]
I would like to find ALL the substrings of my_string
that are in my_list
.
Here is what I tried:
matches = []
if any((match := sub_string) in my_string for sub_string in my_list):
matches.append(match)
The result if I print matches is:
["one"]
I intend for the result to be:
["one", "two", "three"]
Clearly, my code abandons searching for additional matches once it has found one match. Questions:
- How can I edit it to do what I require?
- Is there a faster way of doing what I require?
CodePudding user response:
You can do this with list comprehension,
In [1]: [item for item in my_list if item in my_string]
Out[1]: ['one', 'two', 'three']