Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Find all the strings that are substrings to the given list of strings
Finding strings that are substrings of other strings in a list is a common task in Python. We can use different approaches including list comprehensions with in operator and the any() function.
Using List Comprehension with in Operator
This approach checks if each string from one list appears as a substring in any string from another list ?
main_strings = ["Hello", "there", "how", "are", "you"]
search_strings = ["Hi", "there", "how", "have", "you", "been"]
print("Main strings:", main_strings)
print("Search strings:", search_strings)
# Find strings from search_strings that are substrings of any string in main_strings
result = list(set([search_str for main_str in main_strings
for search_str in search_strings
if search_str in main_str]))
print("Substrings found:", result)
Main strings: ['Hello', 'there', 'how', 'are', 'you'] Search strings: ['Hi', 'there', 'how', 'have', 'you', 'been'] Substrings found: ['there', 'you', 'how']
Using any() Function
The any() function provides a cleaner approach to check if a string exists as a substring in any of the main strings ?
main_strings = ["Hello", "there", "how", "are", "you"]
search_strings = ["Hi", "there", "how", "have", "you", "been"]
result = [search_str for search_str in search_strings
if any(search_str in main_str for main_str in main_strings)]
print("Substrings found:", result)
Substrings found: ['there', 'how', 'you']
Finding Partial Matches
You can also find strings that contain other strings as substrings, not just exact matches ?
main_strings = ["hello", "python", "programming", "tutorial"]
search_strings = ["hell", "prog", "tut", "java"]
# Find which search strings are contained within main strings
result = [search_str for search_str in search_strings
if any(search_str in main_str for main_str in main_strings)]
print("Partial matches:", result)
Partial matches: ['hell', 'prog', 'tut']
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Nested List Comprehension | Complex | Good | Simple cases |
any() Function |
High | Better | Most scenarios |
Conclusion
Use any() with list comprehension for cleaner, more readable code when finding substrings. The nested list comprehension works but is harder to understand for complex substring matching operations.
