简体   繁体   中英

find all strings from list which matches with given few alphabets

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

my_list = ...

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

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM