This is a bit difficult to describe, but I'll do my best.
In Python, I can use string.startswith(tuple)
to test for multiple matches. But startswith
only returns a boolean answer, whether or not it found a match. It is equivalent to any(string.startswith(substring) for substring in inputTuple)
. I am looking for a way to return the rest of the string. So, for example:
>>> fruits = ['apple', 'orange', 'pear']
>>> words1 = 'orange, quagga, etc.'
>>> words2 = 'giraffe, apple, etc.'
>>> magicFunc(words1, fruits)
', quagga, etc.'
>>> magicFunc(words2, fruits)
False
(I'm also okay with the function returning the first matching string, or a list of matching strings, or anything that would enable me to determine where to cut off the string.)
Right now I have this:
remainingString(bigString, searchStrings):
for sub in searchStrings:
if bigString.startswith(sub):
return bigString.partition(sub)[0]
Ick. Is there anything better?
-
Shouldn't this question be asked on Code review.SE ?xlecoustillier– xlecoustillier2016年05月19日 12:01:48 +00:00Commented May 19, 2016 at 12:01
1 Answer 1
There's no easy way to get the info from .startswith
, but you can construct a regular expression that gives you that info.
An example:
import re
prefixes = ("foo", "moo!")
# Add a ^ before each prefix to force a match at the beginning of a string;
# escape() to allow regex-reserved characters like "*" be used in prefixes.
regex_text = "(" + "|".join("^" + re.escape(x) for x in prefixes) + ")"
match = re.search(regex_text, "foobar")
print match.end()
-
Thank you very much! Regex is something I have only just started to realize the power of, and this is perfect for what I need. :)Hactar– Hactar2016年05月21日 01:24:11 +00:00Commented May 21, 2016 at 1:24