Sunday, May 1, 2011

finding substrings in python

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.

From stackoverflow
  • 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 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.

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

0 comments:

Post a Comment