Finding and printing a specific Pattern in a given string
<p>I am writing a code find a specific pattern in a given string using python or perl. I had some success in finding the pattern using C but python or perl usage is mandatory for this assignment and I am very new in both of these lanuages.</p>

<p>My string looks like this (Amino acid sequence) :-</p>

<pre><code> MKTSGNQDEILVIRKGWLTINNIGIMKGGSKEYWFVLTAENLSWYKDDEEKEKKYMLSVDNLKLRDVEKGFMSSKHIFAL
</code></pre>

<p>The pattern I want to find is </p>

<pre><code> KXXXXXX(K\R)XR 
</code></pre>

<p>Please note that Letters between K and K\R are not fixed. However, there is only letter between K\R and R. So, in the given string my pattern is like this and exist between letter no. 54 to 65 (if I counted correctly) based on "smallest pattern" search :-</p>

<pre><code>  KYMLSVDNLKLR
</code></pre>

<p>Previously, I was using C if-else condition to break this given string and printed out word count (not fully successful).</p>

<pre><code>   printf(%c, word[i]);
     if ((word [i] == 'K' || word [i] == 'R' )) &amp;&amp; word [i+2] == 'R') {
        printf("\n");
        printf("%d\n",i);
    }
</code></pre>

<p>I agree It dint capture everything. If anyone can help me help me solving this problem, that would be great.</p>

<p>Regardless of the language, this looks a task suitable for regular expressions.</p>

<p>Here is an example of how you could do the regex in python.  If you want the index where the match starts, you can do:</p>

<pre><code>m = re.search(r'K(?:[A-JL-Z]+?|K)[KR][A-Z]R', s)
print m.start()  # prints index
print m.group()  # prints matching string
</code></pre>

<p>Or as @bunji points out, you an use <code>finditer</code> as well:</p>

<pre><code>for m in re.finditer(r'K(?:[A-JL-Z]+?|K)[KR][A-Z]R', s):
    print m.start()  # prints index
    print m.group()  # prints matching string
</code></pre>

python perl