Python Forum

Full Version: str.startswith(tuple) ... which start?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
str.startswith() supports a tuple (i guess that means not to use a list) to return True if str starts with any str in the tuple. is there an easy way to determine which str it started with, or would i be better off looping through the tuple in my own code and calling str.startswith() for each item and breaking when it gets True?
I would perhaps use bisect for this, if the tuple is sorted
>>> import bisect
>>> t = ('bar', 'baz', 'foo')
>>> w = 'bazaaa'
>>> w.startswith(t)
True
>>> index = bisect.bisect_right(t, w) - 1
>>> t[index]
'baz'
i can sort the tuple when i create it. thanks!