Extract substrings from a string with defined starting and ending points

Viewed 320

I have a list of three sequences looking more or less like this (res):

res = [
     'NVAKMFPQRKFT<STOP>TVQTLMRNGTLLERG<STOP>CCEVSP',

     'QKRMDCNASV<STOP>TVTVQTLMQTL<STOP>TNTPKGG<STOP>',

     'MEKGYADAE<STOP>RKTF<STOP>MTVRAGCCGI<STOP>MK'
]

I want to split every one of these sequences into substrings that start with 'M' and end with (but do not include) < STOP >. These substrings are defined as exons here. I don't want my exons to overlap (the real sequences are much longer than in the sample here). And I want at least two characters in between M and < STOP >.

   exon = list()
   for seq in res:
        string = str(res)
        result = re.search("M(.*?)<STOP>", string)
        if result:
            found = list()
            found = result.group()
            exon.append(found)
   print exon

I want to get a nested list like this:

exon = [

     "['MFPQRKFT', 'MRNGTLLERG']",
     "['MDCNASV', 'MQTL']",
     "['MEKGYADAE', 'MTVRAGCCGI']"
]

But now I am only getting one list with a few exons, and I have < STOP > at the end of each of them.

1 Answers

You could use a pattern with a capture group and re.findall that will return the value of the capture groups

(M.{2,}?)<STOP>
  • ( Capture group 1 (This will be returned by re.findall)
    • M.{2,}? Match M and 2 or more times any char non greedy
  • ) Close group 1
  • <STOP> Match literally

See a regex demo and a Python demo

If you only want to match uppercase chars (The . matches any char except a newline) you can use

(M[A-Z]{2,})<STOP>

Regex demo

For example

import re

exon = list()
res = [
     'NVAKMFPQRKFT<STOP>TVQTLMRNGTLLERG<STOP>CCEVSP',
     'QKRMDCNASV<STOP>TVTVQTLMQTL<STOP>TNTPKGG<STOP>',
     'MEKGYADAE<STOP>RKTF<STOP>MTVRAGCCGI<STOP>MK'
]

for seq in res:
    exon.append(re.findall(r"(M.{2,}?)<STOP>", seq))
    
print(exon)

Output

[
  ['MFPQRKFT', 'MRNGTLLERG'],
  ['MDCNASV', 'MQTL'],
  ['MEKGYADAE', 'MTVRAGCCGI']
]
Related