How to Check if Any or All Multiple Substrings in a List Exist in a String in Python
A common string manipulation task in Python is determining if a target string contains any, or perhaps all, of the substrings from a given list. This is useful for filtering text, keyword searching, or validating input. Python's in
operator combined with the any()
and all()
functions provides efficient and readable ways to perform these checks.
This guide demonstrates how to check if at least one (any) or if all specified substrings are present within a larger string.
The Task: Checking for Multiple Substrings
Given a main string and a list of potential substrings, we want to determine:
- Does the main string contain at least one of the substrings? (OR logic)
- Does the main string contain every single one of the substrings? (AND logic)
Example Data:
main_string = "The quick brown fox jumps over the lazy dog."
substrings_any = ["fox", "cat", "bird"] # We want to know if ANY of these are in main_string
substrings_all = ["quick", "fox", "dog"] # We want to know if ALL of these are in main_string
Check if ANY Substring Exists (any()
)
Use this when you need a True
result if at least one substring from the list is found within the main string.
Using any()
with Generator Expression (Recommended)
This is the most concise and Pythonic way.
main_string = "The quick brown fox jumps over the lazy dog."
substrings_to_check = ["fox", "cat", "lazy"]
# ✅ Check if any substring from the list is in the main string
found_any = any(sub in main_string for sub in substrings_to_check)
print(f"Main string: '{main_string}'")
print(f"Substrings: {substrings_to_check}")
print(f"Any substring found? {found_any}") # Output: True (because 'fox' and 'lazy' are present)
if found_any:
print("--> At least one substring was found.") # This runs
else:
print("--> None of the substrings were found.")
# Example with no matches
substrings_none = ["wolf", "bear"]
found_any_none = any(sub in main_string for sub in substrings_none)
print(f"Any substring found ({substrings_none})? {found_any_none}") # Output: False
(sub in main_string for sub in substrings_to_check)
: A generator expression. It iterates throughsubstrings_to_check
. For eachsub
, it checkssub in main_string
and yieldsTrue
orFalse
.any(...)
: Takes the generated boolean values. It returnsTrue
immediately when it finds the firstTrue
(short-circuiting) orFalse
if all generated values areFalse
.
Getting the First Matching Substring (:=
)
If you need to know which substring caused any()
to return True
(specifically, the first one found), use an assignment expression (:=
, requires Python 3.8+).
main_string = "The quick brown fox jumps over the lazy dog."
substrings_to_check = ["cat", "lazy", "fox"] # Note: lazy appears before fox here
first_match = None
# ✅ Use assignment expression inside any()
if any((match := sub) in main_string for sub in substrings_to_check):
print(f"At least one substring found!")
# 'match' holds the first substring that satisfied 'in main_string'
first_match = match
print(f"The first match found was: '{first_match}'") # Output: 'lazy'
else:
print(f"None of {substrings_to_check} were found.")
print(f"Final value of first_match: {first_match}") # Output: 'lazy'
Getting ALL Matching Substrings (List Comprehension/Filter)
If you need a list of all substrings that were found, use a list comprehension or filter
.
main_string = "The quick brown fox jumps over the lazy dog."
substrings_to_check = ["fox", "cat", "lazy", "dog", "quick"]
# ✅ Use list comprehension to collect all matches
all_matches = [sub for sub in substrings_to_check if sub in main_string]
print(f"All substrings found: {all_matches}")
# Output: All substrings found: ['fox', 'lazy', 'dog', 'quick']
# Alternative using filter()
# all_matches_filter = list(filter(lambda sub: sub in main_string, substrings_to_check))
# print(f"All substrings found (filter): {all_matches_filter}")
Case-Insensitive Check with any()
To ignore case during the check, convert both the main string and each substring to the same case (e.g., lowercase) before the in
comparison.
main_string_upper = "THE QUICK BROWN FOX JUMPS."
substrings_lower = ["fox", "cat", "lazy"]
# ✅ Convert both to lowercase for comparison
found_any_case_insensitive = any(sub.lower() in main_string_upper.lower()
for sub in substrings_lower)
print(f"Main string: '{main_string_upper}'")
print(f"Substrings: {substrings_lower}")
print(f"Any found (case-insensitive)? {found_any_case_insensitive}") # Output: True
Using a for
Loop Alternative
A standard loop achieves the same but is more verbose.
main_string = "The quick brown fox jumps over the lazy dog."
substrings_to_check = ["fox", "cat", "lazy"]
found_one_loop = False # Flag
print("Checking with a loop:")
for sub in substrings_to_check:
print(f"Checking for '{sub}'...")
if sub in main_string:
print(f"--> Found '{sub}'!")
found_one_loop = True
break # Stop as soon as one is found
if found_one_loop:
print("Result: At least one substring was found.")
else:
print("Result: None of the substrings were found.")
Check if ALL Substrings Exist (all()
)
Use this when you need a True
result only if every single substring from the list is present within the main string.
Using all()
with Generator Expression (Recommended)
Similar structure to any()
, but uses all()
.
main_string = "The quick brown fox jumps over the lazy dog."
substrings_all_present = ["quick", "fox", "dog"]
substrings_one_missing = ["quick", "fox", "cat"] # 'cat' is missing
# ✅ Check if ALL substrings are present
all_found_1 = all(sub in main_string for sub in substrings_all_present)
print(f"Main string: '{main_string}'")
print(f"Check if ALL exist: {substrings_all_present}")
print(f"All found? {all_found_1}") # Output: True
if all_found_1:
print("--> All required substrings were found.") # This runs
else:
print("--> Not all required substrings were found.")
# ✅ Check when one is missing
all_found_2 = all(sub in main_string for sub in substrings_one_missing)
print(f"Check if ALL exist: {substrings_one_missing}")
print(f"All found? {all_found_2}") # Output: False (because 'cat' is missing)
if all_found_2:
print("--> All required substrings were found.")
else:
print("--> Not all required substrings were found.") # This runs
(sub in main_string for sub in ...)
: Same generator as before.all(...)
: ReturnsTrue
only if all yielded values areTrue
. It short-circuits and returnsFalse
as soon as it finds the firstFalse
(a substring not present in the main string).
Case-Insensitive Check with all()
Convert both strings to the same case.
main_string_mixed = "FilePath includes /User/Documents/"
required_parts_lower = ["filepath", "/user/", "/documents/"]
# ✅ Convert both to lowercase for comparison
all_found_case_insensitive = all(part.lower() in main_string_mixed.lower()
for part in required_parts_lower)
print(f"Main string: '{main_string_mixed}'")
print(f"Required parts: {required_parts_lower}")
print(f"All found (case-insensitive)? {all_found_case_insensitive}") # Output: True
Using a for
Loop Alternative
Iterate and check if any substring is missing.
main_string = "The quick brown fox jumps over the lazy dog."
substrings_all_present = ["quick", "fox", "dog"]
all_found_loop = True # Assume all exist initially
print("Checking if all exist with a loop:")
for sub in substrings_all_present:
print(f"Checking for '{sub}'...")
if sub not in main_string:
print(f"--> '{sub}' is MISSING!")
all_found_loop = False # Mark as failed
break # Stop as soon as one is missing
if all_found_loop:
print("Result: All required substrings were found.") # This runs
else:
print("Result: Not all required substrings were found.")
Choosing the Right Method
any()
/all()
with Generator Expressions: Recommended for checking existence. They are concise, idiomatic, efficient (short-circuiting), and clearly express the "any" or "all" intent.- List Comprehension /
filter()
: Use these when you need to get the list of actual matches, not just a True/False answer. for
Loop: More verbose. Better if you need complex logic during the check for each substring or if the explicit step-by-step nature is clearer for your context.
Conclusion
Python offers elegant ways to check for the presence of multiple substrings within a larger string:
- To check if any substring exists, use
any(sub in main_string for sub in list_of_subs)
. - To check if all substrings exist, use
all(sub in main_string for sub in list_of_subs)
. - Use
.lower()
or.casefold()
on both strings for case-insensitive comparisons. - Use list comprehensions or
filter()
to retrieve the specific substrings that matched.
These techniques, particularly any()
and all()
with generator expressions, provide efficient and readable solutions for common string searching tasks.