1

Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example
a='KANNKAAN'

OUTPUT;
[KANNKAAN, KANN , KAN ,KAAN]

1
  • If You are satisfied with the provided solution, please mark an answer as accepted, thanks. Commented May 23, 2009 at 9:27

2 Answers 2

2
import re

def occurences(ch_searched, str_input):
    return [i.start() for i in re.finditer(ch_searched, str_input)]

def betweeners(str_input, ch_from, ch_to):
    starts = occurences(ch_from, str_input)
    ends = occurences(ch_to, str_input)
    result = []
    for start in starts:
        for end in ends:
            if start<end:
                result.append( str_input[start:end+1] )
    return result

print betweeners('KANNKAAN', "K", "N")

Is that what You need?

Sign up to request clarification or add additional context in comments.

Comments

1

Another way:

def findbetween(text, begin, end):
    for match in re.findall(begin + '.*' +end, text):
        yield match
        for m in findbetween(match[1:], begin, end):
            yield m
        for m in findbetween(match[:-1], begin, end):
            yield m

>>> list(findbetween('KANNKAAN', 'K', 'N'))
['KANNKAAN', 'KAAN', 'KANN', 'KAN']

Comments

Your Answer

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