Python Forum

Full Version: find unique string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a container of strings. it can be made available in whatever type is most convenient for the best solution, such as a list, or set. what i want to do is find if a given string is a "begins with" substring of exactly one string element of the container. an alternative is to find out the number of such matches or get a list of such matches. for example:
container = ('alignment','aliases')
ops = ('foo','ali','alia','bar')
for op in ops:
    result = find_matches(container,op)
    if len(result)==1:
        print(f'we have a match for "{op}" at "{result[0]}"')
        break
the output should be:
Output:
we have a match for "alia" at "aliases"
Just playing with Python 3.8:

>>> container = ('alignment','aliases')
>>> ops = ('foo','ali','alia','bar')
>>> [match[0] for op in ops if len(match := [cont for cont in container if cont.startswith(op)]) == 1]
['aliases']
>>> container = ('alignment', 'aliases', 'bartender')
>>> [match[0] for op in ops if len(match := [cont for cont in container if cont.startswith(op)]) == 1]
['aliases', 'bartender']