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
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
The simpler is
import re
regx = re.compile('[ ,;:!?.:]')
string = 'I would like an apple.'
search = ['apple','orange', 'banana']
print any(x in regx.split(string) for x in search)
EDIT
Correction, after having read Sven's answer: evidently, string has to not be splited, stupid ! any(x in string for x in search)
works pretty well
If you want no loop:
import re
regx = re.compile('[ ,;:!?.:]')
string = 'I would like an apple.'
search = ['apple','orange', 'banana']
print regx.split(string)
print set(regx.split(string)) & set(search)
result
set(['apple'])
精彩评论