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)

(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?


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
    Commented May 21, 2016 at 1:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.