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.
CodePudding user response:
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
CodePudding user response:
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")
CodePudding user response:
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]
CodePudding user response:
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)