The Python Oracle

How to check if elements of a list are in a string

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping

--

Chapters
00:00 Question
00:37 Accepted answer (Score 6)
01:04 Answer 2 (Score 0)
01:32 Answer 3 (Score 0)
02:15 Thank you

--

Full question
https://stackoverflow.com/questions/1779...

Accepted answer links:
[any()]: http://docs.python.org/2/library/functio...
[all()]: http://docs.python.org/2/library/functio...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #list #ifstatement #element

#avk47



ACCEPTED ANSWER

Score 6


The builtin any() function can help you here:

black_list = ["ab:", "cd:", "ef:", "gh:"]

for line in some_file:
    if ":" in line and not any(x in line for x in black_list):
        pass

It's also possible to get the same effect with all():

for line in some_file:
    if ":" in line and all(x not in line for x in black_list):
        pass

... but I think the first is closer to English, so easier to follow.




ANSWER 2

Score 0


You could check for each "flag" within black_list, and filter lines that contain the black_list. This can be done using all():

for line in some_file:
    filtered = all(i in line for i in black_list)
    if filtered and ':' in line:
        # this line is black listed -> do something
    else:
        # this line is good -> do something

The above checks to see if ALL of the elements of black_list are present. Use any(), if you want to reject a line if any of the elements of black_list are present:

for line in some_file:
    filetered = any(i in line for i in black_list_2)
    if filtered:
        # this line contains at least one element of the black_list
    else:
        # this line is fine



ANSWER 3

Score 0


Your example code makes it look like you're looking for an element in a file, not just in a string. Regardless, you could do something like this, which illustrates doing both with the built-in any()function:

def check_string(text, word_list):
    return any(phrase in text for phrase in word_list)

def check_file(filename, word_list):
    with open(filename) as some_file:
        return any(check_string(line, word_list) for line in some_file)

black_list = ["ab:", "cd:", "ef:", "gh:"]

print check_file('some_file.txt', black_list)