'How to check if any string from a list of strings is a substring of a string?
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.
Solution 1:[1]
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
Solution 2:[2]
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")
Solution 3:[3]
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]
Solution 4:[4]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sash Sinha |
| Solution 2 | Noname |
| Solution 3 | Bilgehan |
| Solution 4 |
