Return names from a list when some letters match

Tags: , ,



How can I return an item from a list if a string matches part of the name?

nameList = ['hospital', 'Conference', 'schools']

string = 'confer'
match = any(string.lower() in name.lower() for name in nameList)
if match:
    # return 'Conference'

Answer

from difflib import get_close_matches

nameList = ['hospital', 'Conference', 'schools']

string = 'confer'

best_match = get_close_matches(string, nameList)
print(best_match)

Output:

['Conference']

You can check more about it here: get_close_matches



Source: stackoverflow