【发布时间】:2014-06-12 17:01:21
【问题描述】:
在python中,您可以检查字符串是否以带有string.endswith(tuple)的元组中的任何项目结尾,但是有没有一种简单的方法可以找出该元组中的哪个项目以它结尾(如果它以一个结尾)而不必须循环遍历元组?
【问题讨论】:
标签: python loops search tuples
在python中,您可以检查字符串是否以带有string.endswith(tuple)的元组中的任何项目结尾,但是有没有一种简单的方法可以找出该元组中的哪个项目以它结尾(如果它以一个结尾)而不必须循环遍历元组?
【问题讨论】:
标签: python loops search tuples
不,没有循环是不可能的。你可以创建一个生成器表达式,像这样
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。
【讨论】: