Home  >  Article  >  Backend Development  >  How to Filter a List of Strings Containing a Specific Substring in Python?

How to Filter a List of Strings Containing a Specific Substring in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-10-20 06:14:29478browse

How to Filter a List of Strings Containing a Specific Substring in Python?

Filtering a List of Strings Based on Their Contents

Given a list of strings, you may encounter the need to extract only those that contain a specific substring. In Python, there are several effective ways to perform this filtering operation.

Using List Comprehensions

One of the simplest and most recommended approaches is to utilize Python's powerful list comprehensions. List comprehensions provide a concise and expressive way to create a new list based on the elements of an existing one. For your specific requirement of filtering strings that contain 'ab', you can employ the following comprehension:

<code class="python">lst = ['a', 'ab', 'abc', 'bac']
result = [k for k in lst if 'ab' in k]</code>

This comprehension iterates through each string in the original list ('a', 'ab', 'abc', 'bac') and checks if it contains the substring 'ab'. If true, it adds the string to the resulting list. This gives you the desired filtered list: ['ab', 'abc'].

Using the filter Function

Another method to filter strings in Python is to use the filter function. This function takes a filter function and an iterable as arguments and returns an iterator that yields the elements of the iterable that satisfy the filter function. In your case, you can use filter as follows:

<code class="python">lst = ['a', 'ab', 'abc', 'bac']
result = list(filter(lambda k: 'ab' in k, lst))</code>

The filter function takes an anonymous function (lambda function) as its first argument, which checks if 'ab' exists in the input string. The second argument is the original list. The result of filter is an iterator, which is then casted to a list using list(). Again, this produces the desired ['ab', 'abc'] list.

While both list comprehensions and the filter function can achieve the desired filtering, list comprehensions are generally preferred for their conciseness and readability, especially for simple filtering tasks like this.

The above is the detailed content of How to Filter a List of Strings Containing a Specific Substring in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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