开发者社区> 问答> 正文

检查字符串是否以元组中的任何元素开头,如果为True,则返回该元素

我有一个值的元组,如下所示:

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

我从用户那里得到输入,并检查输入是否与元组中的任何值匹配,如下所示:

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

我想做的与上面的完全一样,但是返回了匹配的项目。我尝试了许多方法,但没有任何效果。先感谢您。

编辑:在某个时候我以为我可以使用Walrus运算符,但是您会发现它不起作用。

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

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 20:28:51 371 0
1 条回答
写回答
取消 提交回答
  • 该函数接受一个参数和一个参数列表的功能,并将返回使该函数返回真实值的第一个参数。否则,将引发错误:

    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)
    

    回答来源:stackoverflow

    2020-03-24 20:28:57
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载