Question

I'm trying to search words in a text with the function any() of python, I was expecting the same behaviour for the two following, but it's not:

keyword_list=['WASHER', 'SCREW']
all_text  = "test_string"
if any(word in all_text for word in keyword_list):
    print "some of the strings found in str"
else:
    print "no strings found in str"

if (True in (word in all_text for word in keyword_list)):
    print "some of the strings found in str"
else:
    print "no strings found in str"

running inside Spyder 2.2.0 with python 2.7.5(I downloaded the pythonXY package) the results are different from launching python with normal cmd console.

In fact result inside Spyder:

>>> runfile(r'C:\untitled0.py', wdir=r'C:\PythonTestbench')
some of the strings found in str
no strings found in str

In fact result inside command prompt:

>>> runfile(r'C:\untitled0.py', wdir=r'C:\PythonTestbench')
no strings found in str
no strings found in str

Has Spyder environment has another version of any() function, as explained here.

How can I force to not use the function contained into NumPy?

Was it helpful?

Solution

Modify your code in this way:

keyword_list=['WASHER', 'SCREW']
all_text  = "test_string"
print any # so we can see where it comes from
mkgen = lambda: (word in all_text for word in keyword_list)
print list(mkgen()) # to see what we have

if any(mkgen()):
    print "any: some of the strings found in str"
else:
    print "any: no strings found in str"

if (True in mkgen()):
    print "in: some of the strings found in str"
else:
    print "in: no strings found in str"

This program makes it apparent what happens:

  • it prints out the nature of any so you see if it is the "normal one" or a version overwritten by some import *
  • it as well prints out the boolean values generated

If you have managed to find out what's wrong, please use the any() variant. It is much more pythonic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top