Home > Backend Development > Python Tutorial > How Can I Efficiently Find Substrings Within a List of Strings?

How Can I Efficiently Find Substrings Within a List of Strings?

Linda Hamilton
Release: 2024-12-17 07:04:25
Original
302 people have browsed it

How Can I Efficiently Find Substrings Within a List of Strings?

Finding Substrings in Lists

Given a list of strings, we may need to check if a specific string appears within any of its elements. Unlike the common approach of searching for an exact match, we want to identify strings that contain the target string as a substring.

For instance, consider the list xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']. Checking for exact matches of 'abc' using if 'abc' in xs will only detect its exact occurrence and miss substrings like 'abc-123' and 'abc-456'.

To find substrings, we can utilize the in operator in combination with a list comprehension. The code below verifies the presence of 'abc' as a substring in any element of the list:

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

if any("abc" in s for s in xs):
    # 'abc' is present as a substring in at least one element
Copy after login

Alternatively, if we want to retrieve all the elements that include 'abc', we can modify the list comprehension as follows:

xs = ['abc-123', 'def-456', 'ghi-789', 'abc-456']

matching = [s for s in xs if "abc" in s]

print(matching)  # ['abc-123', 'abc-456']
Copy after login

The above is the detailed content of How Can I Efficiently Find Substrings Within a List of Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template