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

Time:01-09

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

you can use filter and lambda function:

>>> list(filter(lambda x: x in y, z))
['test']
  • Related