Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top