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?

asked May 19, 2016 at 11:06
1
  • Shouldn't this question be asked on Code review.SE ? Commented May 19, 2016 at 12:01

1 Answer 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()
answered May 19, 2016 at 12:38
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. :) Commented May 21, 2016 at 1:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.