Python:检查哪个元组项字符串以1结尾(如果它以1结尾)

标签 python loops search tuples

在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/

相关文章:

python - 存储旧值 FiPy

python - 使用一个字典对列表列表的不同元素求和 (Python)

python - 如何分析 DymolaSimulation 的结果(通过 python 接口(interface)模拟)

python - "Failed to locate libpython within timeout period."尝试使用 pyflame 分析不在容器中的 .py 文件时

PHP-While 循环

java - 如何让它运行直到用户输入0或负数?

c - 循环展开以将两个矩阵 NxN 相乘?

database - 分面搜索 : ElasticSearch/Solr or a simple database query?

android - 如何仅根据该记录的部分匹配返回记录?

C 线性搜索无法使用 strcmp 比较两个字符串,编译正常