1

Consider the below code:


fruits = ['apple','orange','mango']

description = 'A mango is an edible stone fruit produced by the tropical tree Mangifera indica'.

I need to check if the description string contains any word from the fruits list.

4 Answers 4

5

Consider using any along with in:

>>> fruits = ['apple', 'orange', 'mango']
>>> description = 'A mango is an edible stone fruit produced by the tropical tree Mangifera indica'
>>> any(f in description for f in fruits)
True
Sign up to request clarification or add additional context in comments.

Comments

1

You could create a list of all the words in the string by splitting it at every " " char. And then check if this list contians the searched words.

fruits = ['apple','orange','mango']
description = 'A mango is an edible stone fruit produced by the tropical tree Mangifera indica'
words = description.split(" ")
for searched in fruits:
   if searched  in words:
      print(f"{searched} found")

Comments

1

You can check this like that:

a=[True if fruit in description else False for fruit in fruits]

And the output will be:

[False, False, True]

Comments

1

A possibility (in case you find the fruit in description syntax confusing) would be to use the __contains__ method, like that:

any(description.__contains__(fruit) for fruit in fruits)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.