在Python中,您可以使用string.endswith(tuple)
检查字符串是否以元组中的任何项目结尾,但是有没有一种简单的方法来找出该元组中的哪个项目以它结尾(如果它以 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
。
关于Python:检查哪个元组项字符串以1结尾(如果它以1结尾),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319230/