Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple NOT IN statements with Python

I need to URLs with three specific specific substrings out of a loop. The following code worked, but I am sure there's a more elegant way to do it:

for node in soup.findAll('loc'):
    url = node.text.encode("utf-8")
    if "/store/" not in url and "/cell-phones/" not in url and "/accessories/" not in url:
        objlist.loc.append(url) 
    else:
        continue

Thank you!

like image 352
tnoznisky Avatar asked Jul 01 '16 17:07

tnoznisky


1 Answers

url = node.text.encode("utf-8")    
sub_strings = ['/store','/cell-phones/','accessories']

if not any(x in url for x in sub_strings):
    objlist.loc.append(url)
else:
    continue

From the docs:

any returns True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
like image 119
Ian Price Avatar answered Sep 17 '22 15:09

Ian Price