Find all list elements that are in a string

Question:

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:

  1. How can I edit it to do what I require?
  2. Is there a faster way of doing what I require?
Asked By: john_mon

||

Answers:

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']

Edit:

If my_string = "onez two three", You can do this,

In [2]: [item for item in my_list if item in my_string.split()]
Out[2]: ['two', 'three']

This approach will work for both cases.

Answered By: Rahul K P
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.