Python Forum
str.startswith(tuple) ... which start? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: str.startswith(tuple) ... which start? (/thread-27095.html)



str.startswith(tuple) ... which start? - Skaperen - May-26-2020

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?


RE: str.startswith(tuple) ... which start? - Gribouillis - May-26-2020

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'



RE: str.startswith(tuple) ... which start? - Skaperen - May-26-2020

i can sort the tuple when i create it. thanks!