How to Filter Strings in a List Based on Substrings?

Susan Sarandon
Release: 2024-10-20 06:13:29
Original
352 people have browsed it

How to Filter Strings in a List Based on Substrings?

Filtering Strings in a List Based on Substrings

Given a list of strings, how can we filter it to include only those that contain a specific substring? For instance, if we have the list ['a', 'ab', 'abc', 'bac'], we would want to obtain the list ['ab', 'abc'].

Solution Using List Comprehension

One efficient method involves using Python's list comprehensions:

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

The list comprehension iterates over each string k in lst and checks if the substring 'ab' exists within it. If true, k is added to the result list.

Alternative Approach Using Filter

Alternatively, we can employ the filter function to achieve the same result:

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

Here, the filter function takes a lambda function that checks for the presence of 'ab' in each string. The resulting iterator is then converted into a list using list.

Conclusion

Both list comprehensions and the filter function offer effective means to filter a list of strings based on specific content. The choice between the two methods depends on personal preference and code readability.

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

source:php
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