What is the fastest way to check if a string contains some characters from any items of a list?
Currently, I’m using this method:
lestring = "Text123"
lelist = ["Text", "foo", "bar"]
for x in lelist:
if lestring.count(x):
print 'Yep. "%s" contains characters from "%s" item.' % (lestring, x)
Is there any way to do it without iteration (which will make it faster I suppose.)?
You can try list comprehension with membership check
Compared to your implementation, though LC has an implicit loop but its faster as there is no explicit function call as in your case with
countCompared to Joe’s implementation, yours is way faster, as the filter function would require to call two functions in a loop,
lambdaandcountJamie’s commented solution is slower for shorter string’s. Here is the test result
If you need Boolean values, for shorter strings, just modify the above LC expression
Or for longer strings, you can do the following
or