views:

2043

answers:

2

hi,

Can you please help me to get the substrings between two characters at each occurrence

For example to get all the substrings between "Q" and "E" in the given example sequence in all occurrences:

ex: QUWESEADFQDFSAEDFS

and to find the substring with minimum length.

+11  A: 
import re
DATA = "QUWESEADFQDFSAEDFS"

# Get all the substrings between Q and E:
substrings = re.findall(r'Q([^E]+)E', DATA)
print "Substrings:", substrings

# Sort by length, then the first one is the shortest:
substrings.sort(key=lambda s: len(s))
print "Shortest substring:", substrings[0]
RichieHindle
+6  A: 

RichieHindle has it right, except that

substrings.sort(key=len)

is a better way to express it than that redundant lambda;-).

If you're using Python 2.5 or later, min(substrings, key=len) will actually give you the one shortest string (the first one, if several strings tie for "shortest") quite a bit faster than sorting and taking the [0]th element, of course. But if you're stuck with 2.4 or earlier, RichieHindle's approach is the best alternative.

Alex Martelli
Good point about the lambda - what was I thinking? 8-)
RichieHindle