How to check if a string starts with a tuple of substring and get the matched one?

Question:

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

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

but how to get which one is matched?

Asked By: رضا پریور

||

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
Answered By: 7koFnMiP

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)]]
Answered By: Ali Sajjad

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())
Answered By: Tomerikoo

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]"
Answered By: JoshuaBox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.