Created
December 13, 2020 06:06
-
-
Save aahnik/2fb49511a66cb2931e51397ab2a3ad61 to your computer and use it in GitHub Desktop.
Search a substring in a list of strings;Python | Finding strings with given substring in list;search a query in a list of strings;re;list comprehension;filter;lambda;re.search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# search a query in a list of strings | |
import re | |
my_list = ['Horrible donkey', 'irritable monkey', 'international idiot'] | |
search_for = 'd' | |
# list comprehension | |
result = [item for item in my_list if search_for in item] | |
print(result) | |
# using filter | |
# The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. | |
result = list(filter(lambda x: search_for in x, my_list)) | |
print(result) | |
# using re | |
result = [item for item in my_list if re.search(search_for, item)] | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output