Reputation: 41
In python you can check if a string ends with any item in a tuple with string.endswith(tuple)
, but is there a simple way to find out which item in that tuple it ends with (if it ends with one at all) without having to loop through the tuple?
Upvotes: 2
Views: 734
Reputation: 239573
No, it is not possible withtout a loop. You can create a generator expression, like this
next((suffix for suffix in suffix_tuple if input_string.endswith(suffix)), None)
For example,
suffix_tuple, input_string = ("s", "r", "t"), "clear"
next((suffix for suffix in suffix_tuple if input_string.endswith(suffix)), None)
# r
Since the default value is None
, if no string in suffix_tuple
matches, it will return None
.
Upvotes: 2