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