if any(word in 'some one long two phrase three' for word in list_):
Answer from kennytm on Stack Overflow
🌐
Moonbooks
en.moonbooks.org › Articles › How-to-check-if-any-word-from-one-list-is-present-in-an-element-of-another-list-in-Python-
How to check if words from one list is present in an element of another list in Python ?
This article will explore how to use these tools to check for the presence of words in a list of strings, and the difference between using any() and all() to refine your checks. ... The any() function allows you to check if at least one condition in an iterable is True.
Discussions

Help!: Check if a Python list item contains a string inside another string but with conditions
Here's two possibilities. If the way you get it done isn't important, you could use a regex because writing string parsing code is always sorta annoying. The regex [aeiou]*[f][aeiou]* would work I think. It matches any number of vowels, then a single "f", and then any number of vowels again. There's also another option. You have two conditions. It seems you want a single "f", which can be checked via word.count("f") == 1 and that every letter (excluding the "f") be a vowel. Essentially, every letter should pass letter == "f" or letter in "aeiou". To check every letter, you can utilize the built-in Python functionall(...). Checking that both these conditions hold, you should get the desired result. More on reddit.com
🌐 r/learnpython
6
1
January 13, 2021
Check if a word is in a string in Python - Stack Overflow
I'm working with Python, and I'm trying to find out if you can tell if a word is in a string. I have found some information about identifying if the word is in the string - using .find, but is ther... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I check if words in a string are elements in a list or lists? - Stack Overflow
test_string = ("this is a test") test_list = [dog, cat, test, is, water] How do I see if 'this' or 'is' or 'a' or 'test' is in test_list? More on stackoverflow.com
🌐 stackoverflow.com
October 20, 2014
Python check if string contains words from specific list of strings - Stack Overflow
435 How to check if a string contains an element from a list in Python · 0 How to check if a string contains a string from a list? 1 Checking if string contains a word that is subset of a word in a list More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 10
17

This function was found by Peter Gibson (below) to be the most performant of the answers here. It is good for datasets one may hold in memory (because it creates a list of words from the string to be searched and then a set of those words):

def words_in_string(word_list, a_string):
    return set(word_list).intersection(a_string.split())

Usage:

my_word_list = ['one', 'two', 'three']
a_string = 'one two three'
if words_in_string(my_word_list, a_string):
    print('One or more words found!')

Which prints One or words found! to stdout.

It does return the actual words found:

for word in words_in_string(my_word_list, a_string):
    print(word)

Prints out:

three
two
one

For data so large you can't hold it in memory, the solution given in this answer would be very performant.

2 of 10
6

To satisfy my own curiosity, I've timed the posted solutions. Here are the results:

TESTING: words_in_str_peter_gibson          0.207071995735
TESTING: words_in_str_devnull               0.55300579071
TESTING: words_in_str_perreal               0.159866499901
TESTING: words_in_str_mie                   Test #1 invalid result: None
TESTING: words_in_str_adsmith               0.11831510067
TESTING: words_in_str_gnibbler              0.175446796417
TESTING: words_in_string_aaron_hall         0.0834425926208
TESTING: words_in_string_aaron_hall2        0.0266295194626
TESTING: words_in_str_john_pirie            <does not complete>

Interestingly @AaronHall's solution

def words_in_string(word_list, a_string):
    return set(a_list).intersection(a_string.split())

which is the fastest, is also one of the shortest! Note it doesn't handle punctuation next to words, but it's not clear from the question whether that is a requirement. This solution was also suggested by @MIE and @user3.

I didn't look very long at why two of the solutions did not work. Apologies if this is my mistake. Here is the code for the tests, comments & corrections are welcome

from __future__ import print_function
import re
import string
import random
words = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']

def random_words(length):
    letters = ''.join(set(string.ascii_lowercase) - set(''.join(words))) + ' '
    return ''.join(random.choice(letters) for i in range(int(length)))

LENGTH = 400000
RANDOM_STR = random_words(LENGTH/100) * 100
TESTS = (
    (RANDOM_STR + ' one two three', (
        ['one', 'two', 'three'],
        set(['one', 'two', 'three']),
        False,
        [True] * 3 + [False] * 7,
        {'one': True, 'two': True, 'three': True, 'four': False, 'five': False, 'six': False,
            'seven': False, 'eight': False, 'nine': False, 'ten':False}
        )),

    (RANDOM_STR + ' one two three four five six seven eight nine ten', (
        ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'],
        set(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']),
        True,
        [True] * 10,
        {'one': True, 'two': True, 'three': True, 'four': True, 'five': True, 'six': True,
            'seven': True, 'eight': True, 'nine': True, 'ten':True}
        )),

    ('one two three ' + RANDOM_STR, (
        ['one', 'two', 'three'],
        set(['one', 'two', 'three']),
        False,
        [True] * 3 + [False] * 7,
        {'one': True, 'two': True, 'three': True, 'four': False, 'five': False, 'six': False,
            'seven': False, 'eight': False, 'nine': False, 'ten':False}
        )),

    (RANDOM_STR, (
        [],
        set(),
        False,
        [False] * 10,
        {'one': False, 'two': False, 'three': False, 'four': False, 'five': False, 'six': False,
            'seven': False, 'eight': False, 'nine': False, 'ten':False}
        )),

    (RANDOM_STR + ' one two three ' + RANDOM_STR, (
        ['one', 'two', 'three'],
        set(['one', 'two', 'three']),
        False,
        [True] * 3 + [False] * 7,
        {'one': True, 'two': True, 'three': True, 'four': False, 'five': False, 'six': False,
            'seven': False, 'eight': False, 'nine': False, 'ten':False}
        )),

    ('one ' + RANDOM_STR + ' two ' + RANDOM_STR + ' three', (
        ['one', 'two', 'three'],
        set(['one', 'two', 'three']),
        False,
        [True] * 3 + [False] * 7,
        {'one': True, 'two': True, 'three': True, 'four': False, 'five': False, 'six': False,
            'seven': False, 'eight': False, 'nine': False, 'ten':False}
        )),

    ('one ' + RANDOM_STR + ' two ' + RANDOM_STR + ' threesome', (
        ['one', 'two'],
        set(['one', 'two']),
        False,
        [True] * 2 + [False] * 8,
        {'one': True, 'two': True, 'three': False, 'four': False, 'five': False, 'six': False,
            'seven': False, 'eight': False, 'nine': False, 'ten':False}
        )),

    )

def words_in_str_peter_gibson(words, s):
    words = words[:]
    found = []
    for match in re.finditer('\w+', s):
        word = match.group()
        if word in words:
            found.append(word)
            words.remove(word)
            if len(words) == 0: break
    return found

def words_in_str_devnull(word_list, inp_str1):
    return dict((word, bool(re.search(r'\b{}\b'.format(re.escape(word)), inp_str1))) for word in word_list)


def words_in_str_perreal(wl, s):
    i, swl, strwords = 0, sorted(wl), sorted(s.split())
    for w in swl:
        while strwords[i] < w:  
            i += 1
            if i >= len(strwords): return False
        if w != strwords[i]: return False
    return True

def words_in_str_mie(search_list, string):
    lower_string=string.lower()
    if ' ' in lower_string:
        result=filter(lambda x:' '+x.lower()+' ' in lower_string,search_list)
        substr=lower_string[:lower_string.find(' ')]
        if substr in search_list and substr not in result:
            result+=substr
        substr=lower_string[lower_string.rfind(' ')+1:]
        if substr in search_list and substr not in result:
            result+=substr
    else:
        if lower_string in search_list:
            result=[lower_string]

def words_in_str_john_pirie(word_list, to_be_searched):
    for word in word_list:
        found = False
        while not found:
            offset = 0
            # Regex is expensive; use find
            index = to_be_searched.find(word, offset)
            if index < 0:
                # Not found
                break
            if index > 0 and to_be_searched[index - 1] != " ":
                # Found, but substring of a larger word; search rest of string beyond
                offset = index + len(word)
                continue
            if index + len(word) < len(to_be_searched) \
                    and to_be_searched[index + len(word)] != " ":
                # Found, but substring of larger word; search rest of string beyond
                offset = index + len(word)
                continue
            # Found exact word match
            found = True    
    return found

def words_in_str_gnibbler(words, string_to_be_searched):
    word_set = set(words)
    found = []
    for match in re.finditer(r"\w+", string_to_be_searched):
        w = match.group()
        if w in word_set:
             word_set.remove(w)
             found.append(w)
    return found

def words_in_str_adsmith(search_list, big_long_string):
    counter = 0
    for word in big_long_string.split(" "):
        if word in search_list: counter += 1
        if counter == len(search_list): return True
    return False

def words_in_string_aaron_hall(word_list, a_string):
    def words_in_string(word_list, a_string):
        '''return iterator of words in string as they are found'''
        word_set = set(word_list)
        pattern = r'\b({0})\b'.format('|'.join(word_list))
        for found_word in re.finditer(pattern, a_string):
            word = found_word.group(0)
            if word in word_set:
                word_set.discard(word)
                yield word
                if not word_set:
                    raise StopIteration
    return list(words_in_string(word_list, a_string))

def words_in_string_aaron_hall2(word_list, a_string):
    return set(word_list).intersection(a_string.split())

ALGORITHMS = (
        words_in_str_peter_gibson,
        words_in_str_devnull,
        words_in_str_perreal,
        words_in_str_mie,
        words_in_str_adsmith,
        words_in_str_gnibbler,
        words_in_string_aaron_hall,
        words_in_string_aaron_hall2,
        words_in_str_john_pirie,
        )

def test(alg):
    for i, (s, possible_results) in enumerate(TESTS):
        result = alg(words, s)
        assert result in possible_results, \
            'Test #%d invalid result: %s ' % (i+1, repr(result))

COUNT = 10
if __name__ == '__main__':
    import timeit
    for alg in ALGORITHMS:
        print('TESTING:', alg.__name__, end='\t\t')
        try:
            print(timeit.timeit(lambda: test(alg), number=COUNT)/COUNT)
        except Exception as e:
            print(e)
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-test-if-string-contains-element-from-list
Python - Test if string contains element from list - GeeksforGeeks
July 11, 2025 - The loop iterates through each element in the list 'el' and checks if it exists in the string 's' using the 'in' operator. If a match is found, the loop exits early using break, which saves unnecessary iterations. Using set intersection method is effective when both the string and the list of elements are relatively short. ... s = "Python is powerful and versatile." el = ["powerful", "versatile", "fast"] # Split the string into individual words using the split() method' res = bool(set(s.split()) & set(el)) print(res)
🌐
Python Forum
python-forum.io › thread-28526.html
how to check if string contains ALL words from the list?
May 18, 2021 - Hi guys, How can i check if string contains all words from the list? some_string = 'there is a big apple, but i like banana more than orange' some_list = ['apple', 'banana', 'orange']It should return True
🌐
TutorialsPoint
tutorialspoint.com › python-program-to-test-if-string-contains-element-from-list
Python program to find the String in a List
January 27, 2023 - words = ['programming', 'python', 'coding', 'development'] substring = 'prog' # Check if any word contains the substring found = any(substring in word for word in words) print(f"Words containing '{substring}': {found}") # Find all words containing the substring matching_words = [word for word in words if substring in word] print(f"Matching words: {matching_words}") Words containing 'prog': True Matching words: ['programming'] A list of integers and strings is defined and displayed on the console.
🌐
Reddit
reddit.com › r/learnpython › help!: check if a python list item contains a string inside another string but with conditions
r/learnpython on Reddit: Help!: Check if a Python list item contains a string inside another string but with conditions
January 13, 2021 -

I have two days learning python but I really need to do that code. I also posted this question in StackOverflow but it got downvoted the first second.

I want to make a function to print all the words that contain a specific consonant (only one) and any amount of vowels, but I don't know how to introduce the conditions here.

I made a list with 4 elements via the input method (I know I use a different way), and a method that prints all the words that include the letter "f", but as I said, it needs to be more specific (only one consonant, "f" in this case, and any amount of vowels):

list = []  
for x in range (4):     
    words = str(input("Type a word "))     
    list.append(words)  

#This method kinda works, but it needs to be more specific.   
matching = [s for s in list if "f" in s] 
print(matching) 

In my code, if I have words with the letter "f", I'll get a list with all the words containing any amount of "f" letters and any other consonant, but I just want one consonant "f" and vowels, not the other consonants.

My desired result is like

list = [fox, alfa, fa, real, fou]

#['fa', 'fou']

Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-find-string-in-list
Python Find String in List: Methods and Examples | DigitalOcean
Learn how to find a string in a Python list using in, index(), list comprehension, and regex. See practical, runnable code examples and start today.
🌐
Stack Overflow
stackoverflow.com › questions › 26455865 › how-do-i-check-if-words-in-a-string-are-elements-in-a-list-or-lists
python - How do I check if words in a string are elements in a list or lists? - Stack Overflow
October 20, 2014 - shouldn't test_list = [dog, cat, test, is, water] rather be test_list = ['dog', 'cat', 'test', 'is', 'water']? ... Yeah I was in a hurry I make that mistake often. ... Use str.split to split the string and use any to see if any of the words in the string are in your list:
🌐
Stack Overflow
stackoverflow.com › questions › 68111704 › python-check-if-string-contains-words-from-specific-list-of-strings
Python check if string contains words from specific list of strings - Stack Overflow
I have two inputs, constants and order_string above. I want to check if order_string contain any substring that start from '{' or '{{', like {{first_name}}, then this substring {{first_name}} must be in constant variable. If it's not in the list then order_string contain invalid substring.
Top answer
1 of 3
2

Issues

Your for-loop iterates over each character in the message. So it has 176 iterations, each checking if character is list (! probably not what you want): if i == words

Solution

Other than answered by Riccardo with the elegant and concise but advanced construct of list-comprehension you could also fix your loop:

(A) You can either just turn your search around if word in message.

(B) Alternatively first split the message to chunks (words), e.g. by whitespace as delimiter. Then iterate over each of those chunks and test if in your list.

words = ["Lorem", "facilisis", "consectetur", "iaculis", "dolor"]

message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " \
          "Aliquam aliquet facilisis orci, scelerisque iaculis odio dignissim nec. " \
          "Vestibulum luctus erat sit amet suscipit commodo"

# (A) in approach 
for w in words:
    if w in message:
        print(f"(A) Word found: {w}")

# (B) split approach 
for chunk in message.split():
    if chunk in words:
        print(f"(B) Word found: {chunk}")

Prints a different ordered but same set of 5 words for each approach:

(A) Word found: Lorem
(A) Word found: facilisis
(A) Word found: consectetur
(A) Word found: iaculis
(A) Word found: dolor
(B) Word found: Lorem
(B) Word found: dolor
(B) Word found: consectetur
(B) Word found: facilisis
(B) Word found: iaculis

Note: the default separator when invoking str.split() without arguments is a whitespace (space, tab, new-line, etc.).

Bonus: improved splitting

To not only split on a single separator character or default whitespace use the string constants like:

  • string.whitespace, or regex equivalent shorthand \s
  • string.punctuation

in combination with re.split (split by regular-expression) you can even improve your split and find words next to a line-break like 'Vestibulum' or words next to a punctuation-mark like ['amet', 'elit', 'orci', 'nec']:

message = "\tLorem ipsum dolor sit amet, consectetur adipiscing elit. " \
          "Aliquam aliquet facilisis orci, scelerisque iaculis odio dignissim nec.\n" \
          "Vestibulum luctus erat sit amet suscipit commodo"
words = ['amet', 'elit', 'orci', 'nec', 'Vestibulum']

import string
import re

sep_regex = '['+string.punctuation+'\s]'  # use \s instead string.whitespace
chunks = re.split(sep_regex, message)
found_words = [w for w in chunks if w in words]
print(found_words)

Prints:

['amet', 'elit', 'orci', 'nec', 'Vestibulum', 'amet']

Note: It contains 'amet' twice because it was found twice. To get only the unique words found convert it to a set using set(found_words)

See also:

  • Regex to split words in Python
  • https://codereview.stackexchange.com/questions/230126/string-operation-to-split-on-punctuation
2 of 3
0

Try this:

words_found = [word for word in words if word in message]
🌐
Stack Abuse
stackabuse.com › bytes › check-if-a-string-contains-an-element-from-a-list-in-python
Check if a String Contains an Element from a List in Python
October 6, 2023 - If it does, it adds the element to the found_elements list. When you print found_elements, it displays the elements from my_list that are found in my_string. ... In Python, the any() function is a built-in function that returns True if any element of an iterable is truethy.
🌐
AskPython
askpython.com › python › list › find-string-in-list-python
Find a string in a List in Python - AskPython
February 16, 2023 - In Python, the in operator allows you to determine if a string is present a list or not. The operator takes two operands, a and b, and the expression a in b returns a boolean value.