The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 How To Check If Elements Of A List Are In A String
00:27 Accepted Answer Score 6
00:50 Answer 2 Score 0
01:23 Answer 3 Score 0
01:44 Thank you

--

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

--

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)