If a string does not contain any of the list of strings in python

I have a list of lines from which I want to find every line that has "http: //" in it, but does not have "lulz", "lmfao", ".png" or any other elements in the list of lines in it. How can i do this?

My instincts tell me to use regular expressions, but I have a moral objection to witchcraft.

+6
source share
3 answers

Here is an option that is quite extensible if the list of lines to exclude is large:

exclude = ['lulz', 'lmfao', '.png'] filter_func = lambda s: 'http://' in s and not any(x in s for x in exclude) matching_lines = filter(filter_func, string_list) 

Alternative comparison:

 matching_lines = [line for line in string_list if filter_func(line)] 
+10
source

This is almost equivalent to a FJ solution, but uses expressions instead of lambda expressions and a filter function:

 haystack = ['http://blah', 'http://lulz', 'blah blah', 'http://lmfao'] exclude = ['lulz', 'lmfao', '.png'] http_strings = (s for s in haystack if s.startswith('http://')) result_strings = (s for s in http_strings if not any(e in s for e in exclude)) print list(result_strings) 

When I run this, it prints:

 ['http://blah'] 
+3
source

Try the following:

 for s in strings: if 'http://' in s and not 'lulz' in s and not 'lmfao' in s and not '.png' in s: # found it pass 

Another option if you need your more flexible options:

 words = ('lmfao', '.png', 'lulz') for s in strings: if 'http://' in s and all(map(lambda x, y: x not in y, words, list(s * len(words))): # found it pass 
+2
source

Source: https://habr.com/ru/post/910217/


All Articles