0

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?

1
0

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()
1
  • 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 May 21 '16 at 1:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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