Search code examples
python-3.xstringstartswith

Check if a string startswith any element in a tuple, if True, return that element


I have a tuple of values as follows:

commands = ("time", "weather", "note")

I get an input from the user and I check if the input matches any value in the tuple as follows:

if user_input.startswith(commands):
    # Do stuff based on the command

What I would like to do is exactly as the above, but with the matched item returned. I tried many methods, but nothing really worked. Thank you in advance.

Edit: At some point I thought I could use the Walrus operator, but you would figure out it wouldn't work.

if user_input.startswith(returned_command := commands):
    command = returned_command
    # actually command only gets the commands variable.

Solution

  • This function takes a function of one argument and a list of arguments, and will return the first argument that makes the function return a truthy value. Otherwise, it will raise an error:

    def first_matching(matches, candidates):
        try:
            return next(filter(matches, candidates))
        except StopIteration:
            raise ValueError("No matching candidate")
    
    result = first_matching(user_input.startswith, commands)