Skip to content
Advertisement

Return names from a list when some letters match

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'

Advertisement

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement