check if a string start with a tuple of substring and get the matched one in python

Viewed 441

I know how to check if a string starts with some substring like this:

text.startswith(("one", "two", "three", "four")) 

but how get which one is matched? is there a direct way to get matched one?

5 Answers

You could loop over the elements in the tuple:

mytuple = ("one", "two", "three", "four")
text = "one dog"
for i in mytuple:
    if text.startswith(i):
        print(i)
        break
>>> one

If you want to use regex, see Tomerikoo's answer

You can use regex by building a pattern from the tuple and then extract the match:

import re

subs = ("one", "two", "three", "four")
text = "three and a half"

if r := re.match("|".join(subs), text):
    print(r.group())
else:
    print("No match found")

Using re.match, this provides the same functionality as str.startswith.


For versions older than Python 3.8, use explicit assignment:

r = re.match("|".join(subs), text)
if r:
    print(r.group())

use a comprehension and next:

>>> text = "two dogs"
>>> lst = ("one", "two", "three", "four")
>>> next((item for item in lst if text.startswith(item)),None)
'two'

item for item in lst if text.startswith(item) yields item if condition is True. next iterates manually on the expression at most once.

If no string matches, the expression returns None. First match ends the search.

One line version. This will give the list of all words which appear in the start of text.

startMatches = [word for word in ("one","two","three","four") if word == text[:len(word)]]

Also a oneliner with list comprehension:

text = 'three-dimensional'
match_idxs = [i for i, substr in enumerate(("one", "two", "three", "four")) if text.startswith(substr)]
print('matching indexes: ', match_idxs)

>>> "matching indexes: [2]"
Related