Home >Backend Development >Python Tutorial >How to Extract Strings Containing a Specific Substring in Python?

How to Extract Strings Containing a Specific Substring in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-20 06:18:29593browse

How to Extract Strings Containing a Specific Substring in Python?

Identifying Strings Containing a Specific Substring

To extract a list of specific strings that contain a given substring, we can leverage Python's powerful filtering capabilities. One effective approach is to utilize list comprehensions, as demonstrated below:

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

This comprehension method conveniently filters the list, retaining only those strings that include the substring 'ab'. The result is a new list containing:

['ab', 'abc']

An alternative approach is to employ the filter function, which offers a concise solution:

<code class="python">list(filter(lambda k: 'ab' in k, lst))</code>

In Python 2, the filter function returns an iterator, which can be cast to a list using the list function. In Python 3, the filter function returns an iterator by default.

While both methods achieve the same desired outcome, list comprehensions are generally considered a more concise and Pythonic way to filter lists, as they provide a straightforward and readable implementation.

The above is the detailed content of How to Extract 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