Home > Enterprise >  find all strings from list which matches with given few alphabets
find all strings from list which matches with given few alphabets

Time:06-16

I am building a simple function to search through some data from the list. I am trying to search string from list matches some characters from start of string.

Like :-

my_list = ["com truise", "bill james", "bill bates", "bustin jeiber"]

def search_from_list(searched_word):
    for word in my_list:
        if searched_word == word:
            print("Matched")
            print("All words"   __full_word_that_matched__)

search_from_list("bi")

and if user calls the function with argument "bi" then I am trying to get strings which matched that string "bi" like :-

["bill james", "bill bates"]

But it is not working, I have tried many methods like :-

def search_from_list(searched_word):
    my_list = ["com truise", "bill james", "bill bates", "bustin jeiber"]

    print re.findall(r"(?=(" '|'.join(my_list) r"))", searched_word)

searched_word("bi")

But it returned empty

then I tried

def search_from_list(searched_word):
    words = re.findall(r'\w ', searched_word)
    return [word for word in words if word in my_list]

n = search_from_list("bi")

It also showed me empty list

Any help would be much Appreciated. Thank You in Advance

CodePudding user response:

my_list = ...

def search_from_list(substring):
    return [string for string in my_list if substring in string]

CodePudding user response:

with regular expression

import re
my_list = ["com truise", "bill james", "bill bates", "bustin jeiber"]

def search_from_list(searched_word):
    return [word for word in my_list if re.match(searched_word, word)]

print(search_from_list("bi"))
  • Related