Reputation: 698
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?
Upvotes: 3
Views: 1070
Reputation: 140256
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.
Upvotes: 1
Reputation: 477
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
Upvotes: 4
Reputation: 19422
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())
Upvotes: 4
Reputation: 4490
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)]]
Upvotes: 0
Reputation: 775
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]"
Upvotes: 0