Skip to content

Instantly share code, notes, and snippets.

@aahnik
Created December 13, 2020 06:06
Show Gist options
  • Save aahnik/2fb49511a66cb2931e51397ab2a3ad61 to your computer and use it in GitHub Desktop.
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
# 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)
@aahnik
Copy link
Author

aahnik commented Dec 13, 2020

output

['Horrible donkey', 'international idiot']
['Horrible donkey', 'international idiot']
['Horrible donkey', 'international idiot']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment