I know can use string.find()
to find a substring in a string.
But what is the easiest way to find out if one of the array items has a substring match in a string without using a loop?
Pseudocode:
string = 'I would like an apple.'
search = ['apple','orange', 'banana']
string.find(search) # == True
The Array.find() method returns the first matching item in an array. Just like the Array. filter() method, you call it on the array, and pass in a callback function that returns a boolean: true if the item is a match, and false if it's not.
Search for string in JS array – use Array. indexOf() can be used to find out if an array contains an element, just like Array. includes() above.
JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.
IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.
You could use a generator expression (which somehow is a loop)
any(x in string for x in search)
The generator expression is the part inside the parentheses. It creates an iterable that returns the value of x in string
for each x
in the tuple search
. x in string
in turn returns whether string
contains the substring x
. Finally, the Python built-in any()
iterates over the iterable it gets passed and returns if any of its items evaluate to True
.
Alternatively, you could use a regular expression to avoid the loop:
import re
re.search("|".join(search), string)
I would go for the first solution, since regular expressions have pitfalls (escaping etc.).
Strings in Python are sequences, and you can do a quick membership test by just asking if one string exists inside of another:
>>> mystr = "I'd like an apple"
>>> 'apple' in mystr
True
Sven got it right in his first answer above. To check if any of several strings exist in some other string, you'd do:
>>> ls = ['apple', 'orange']
>>> any(x in mystr for x in ls)
True
Worth noting for future reference is that the built-in 'all()' function would return true only if all items in 'ls' were members of 'mystr':
>>> ls = ['apple', 'orange']
>>> all(x in mystr for x in ls)
False
>>> ls = ['apple', 'like']
>>> all(x in mystr for x in ls)
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With