Python Forum
str.startswith(tuple) ... which start?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
str.startswith(tuple) ... which start?
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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'
Reply
#3
i can sort the tuple when i create it. thanks!
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020