Python Forum

Full Version: string between two strings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i want to get the string that is between (the first instances of) two strings, a and b (in that order).  i can do it like:

what_was_between = original_string.split(a)[1].split(b)[0]
is there a shorter, sweeter, and/or more elegant way?  i am dreaming of:

def between(s,a,b):
    return s.split(a)[1].split(b)[0]
should i go with that?
I think a regular expression is the way to go, if you're looking for simplicity. A regex will also have the advantage of performance, having been optimized in C, and efficiency, doing the minimum string traversal and not needing to create intermediate strings.
(Dec-15-2016, 05:10 AM)micseydel Wrote: [ -> ]I think a regular expression is the way to go, if you're looking for simplicity. A regex will also have the advantage of performance, having been optimized in C, and efficiency, doing the minimum string traversal and not needing to create intermediate strings.

can that be done in cases where the bounding strings or the string to extract are regular expressions, or subsets or supersets of them?

edit1:

the first (but not the only) project using this will be extracting from between constants '<' and '>'.
(Dec-15-2016, 08:39 AM)Skaperen Wrote: [ -> ]the first (ut not the only) project using this will be extracting from between constants '<' and '>'.


http://stackoverflow.com/questions/17323...gs#1732454