Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find array item in a string

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
like image 252
Sindre Sorhus Avatar asked May 02 '11 15:05

Sindre Sorhus


People also ask

How do I find a specific item in an array?

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.

How do I find a string in an array?

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.

How do you find if an array contains a specific string in JavaScript?

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.

Can you use indexOf for an array?

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.


2 Answers

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.).

like image 177
Sven Marnach Avatar answered Oct 05 '22 03:10

Sven Marnach


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
like image 41
jonesy Avatar answered Oct 05 '22 05:10

jonesy