【问题标题】:Python: Check which tuple item string ends with, if it ends with one at allPython:检查哪个元组项字符串以一个结尾,如果它以一个结尾
【发布时间】:2014-06-12 17:01:21
【问题描述】:

在python中,您可以检查字符串是否以带有string.endswith(tuple)的元组中的任何项目结尾,但是有没有一种简单的方法可以找出该元组中的哪个项目以它结尾(如果它以一个结尾)而不必须循环遍历元组?

【问题讨论】:

    标签: python loops search tuples


    【解决方案1】:

    不,没有循环是不可能的。你可以创建一个生成器表达式,像这样

    next((suffix for suffix in suffix_tuple if input_string.endswith(suffix)), None)
    

    例如,

    suffix_tuple, input_string = ("s", "r", "t"), "clear"
    next((suffix for suffix in suffix_tuple if input_string.endswith(suffix)), None)
    # r
    

    由于默认值为None,如果suffix_tuple中没有字符串匹配,则返回None

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 2013-08-23
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多