Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if an array of strings contains a substring of another string

Let’s say I have an array of strings, along with some other sentences ie.


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

example1 = 'John really enjoys melons'
example2 = 'John would like an apple'

I want to return True if any of the values inside ‘fruits’ are a valid substring of text1 or text2.

So in this case text1 is going to be false, and text2 is going to be true. Obviously I can iterate over every value in fruits and check if it is present in the example text one by one for each example.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, my actual data has hundreds of ‘examples’ I want to check, and my ‘fruits’ array is much longer. Is there a short/concise way to do this in Python? ie. Some sort of function that can be called instead of having to iterate over each value in "fruits" for every example.

>Solution :

You could use any() with a generator expression to iterate over all the fruits: (It short-circuits, so once it finds one that’s True, it stops)

any(fruit in example1 for fruit in fruits) # True
any(fruit in example2 for fruit in fruits) # False
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading