Search a string using list elements for matches and return the match found

Question:

I am trying to search a string for any elements in a list, and return the match found.

I currently have


y = "test string"
z = ["test", "banana", "example"]

if any(x in y for x in z):
   match_found = x
   print("Match: " + match_found)

This obviously does not work, but is there a good way to accomplish this besides using a for loop and an if loop?

Asked By: Testing Apps

||

Answers:

I think you looking for this

text = "test string"
words = ["test", "banana", "example"]

found_words = [word for word in words if word in text]
print(found_words)

result

['test']
Answered By: Ronin

I think you should do:

res = [x for x in z if x in y]
print(f"Match: {', '.join(res) if res else 'no'}")

# Output
Match: test
Answered By: Corralien

You can do the below:

y = "test string"
z = ["test", "banana", "example"]

for x in z:
 if x in y:
  match_found = x
  print("Match: " + match_found)
  break
Answered By: Yash Shah

you can use filter and lambda function:

>>> list(filter(lambda x: x in y, z))
['test']
Answered By: Hackaholic
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.