Answers.Body: <p>This is easy just replace <code>findall</code> with <code>finditer</code> in the above code. The index will then appear where the match first appears and where it stops. However, you will to parse the <code>finditer</code> object which in the code is <code>s</code></p>
  <p>Then replace</p>
  <pre><code>print '%s:%s' %(name,s)
  </code></pre>
  <p>with</p>
  <pre><code>for match_obj in s:
      # print each re.Match object
      print(match_obj)
      
      # extract each matching number
      print(match_obj.group())
  </code></pre>
  <p>That should work. When it does you simply pass the <code>match_obj</code> and <code>match_obj.group()</code> to a file by replacing <code>s</code> with <code>match_obj, match_obj.group()</code></p>
  <p>Thus replace</p>
  <pre><code>  out.write('%s:\t%s\n' %(name,s))
  </code></pre>
  <p>with</p>
  <pre><code>  out.write('%s:\t%s\t%s\n' %(name,match_obj,match_obj.group()))
  </code></pre>
  <p>You might need to do an append BTW.</p>
  <p>thus replace</p>
  <pre><code>out=open(&quot;results.csv&quot;,'w')
  </code></pre>
  <p>with</p>
  <pre><code>import os
  if os.path.exists(&quot;results.csv&quot;):
      os.unlink (&quot;results.csv&quot;)
  out=open(&quot;results.csv&quot;,'a')
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-11-13T06:45:19.233Z
Answers.Text: Thank you so much for your suggestion, I am still new python user and will read up on biopython. With regards to the code will it now be: `else:s=re.finditer (pattern,line)` 
   `print'%s:%' %(name,s)`  ? Also by parse the finditer object what does that mean? I am struggling to link it to the original code. Could you perhaps try to edit your answer such that it looks like the original code, so that I can see where the changes will need to be made.
Answers.UserDisplayName: thole
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-11-13T04:49:33.200Z
Answers.LastActivityDate: 2022-11-13T16:34:42.213Z
Answers.LastEditDate: 2022-11-13T16:34:42.213Z
Answers.UserDisplayName: M__
Body: <p>I am able to find matching motifs on a single sequence, as well as their position as shown below :</p>
  <pre><code>demo = &quot;ABCLXLYLZLABC&quot;
  motif=&quot;L.L.L&quot;
  for element in re.finditer(motif,demo):
      print(element.start(),element.end,element.group())
  </code></pre>
  <p>This works and gives me the desired output which is:
  <code> 3 8 LXLYL</code></p>
  <p>Now I want to know how can I then do this same process but on a multifasta file.
  As done in this example script from <a href="https://www.biostars.org/p/14305/" rel="nofollow noreferrer">https://www.biostars.org/p/14305/</a> .</p>
  <p>The protein sequences on the file are :</p>
  <pre><code>&gt; P1
  MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP
  MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ
  FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD
  IIEKNESGWWFVSTAEEQGWVPATCLEGQDGVQDEFSLQPEEEEKYTVIYPYTARDQDEM
  NLERGAVVEVVQKNLEGWWKIRYQGKEGWAPASYLKKNSGEPLPPKLGPSSPAHSGALDL
  DGVSRHQNAMGREKELLNNQRDGRFEGRLVPDGDVKQRSPKMRQRPPPRRDMTIPRGLNL
  &gt;P2
   MAEVRKFTKRLSKPGTAAELRQSVSEAVRGSVVLEKAKLVEPLDYENVITQRKTQIYSDP
   LRDLLMFPMEDISISVIGRQRRTVQSTVPEDAEKRAQSLFVKECIKTYSTDWHVVNYKYE
   DFSGDFRMLPCKSLRPEKIPNHVFEIDEDCEKDEDSSSLCSQKGGVIKQGWLHKANVNST
   ITVTMKVFKRRYFYLTQLPDGSYILNSYKDEKNSKESKGCIYLDACIDVVQCPKMRRHAF
   ELKMLDKYSHYLAAETEQEMEEWLIMLKKIIQINTDSLVQEKKDTVEAIQEEETSSQGKA
   ENIMASLERSMHPELMKYGRETEQLNKLSRGDGRQNLFSFDSEVQRLDFSGIEPDVKPFE
   EKCNKRFMVNCHDLTFNILGHIGDNAKGPPTNVEPFFINLALFDVKNNCKISADFHVDLN
   PPSVREMLWGTSTQLSNDGNAKGFSPESLIHGIAESQLCYIKQGIFSVTNPHPEIFLVVR
  &gt;P3
  GDDSEWLKLPVDQKCEHKLWKARLSGYEEALKIFQKIKDEKSPEWSKYLGLIKKFVTDS
  NAVVQLKGLEAALVYVENAHVAGKTTGEVVSGVVSKVFNQPKAKAKELGIEICLMYVEIE
  KGESVQEELLKGLDNKNPKIIVACIETLRKALSEFGSKIISLKPIIKVLPKLFESRDKAV
  RDEAKLFAIEIYRWNRDAVKHTLQNINSVQLKELEEEWVKLPTGAPKPSRFLRSQQELEA
  KLEQQQSAGGDAEGGGDDGDEVPQVDAYELLDAVEILSKLPKDFYDKIEAKKWQERKEAL
  EAVEVLVKNPKLEAGDYADLVKALKKVVGKDTNVMLVALAAKCLTGLAVGLRKKFGQYAG
  HVVPTILEKFKEKKPQVVQALQEAIDAIFLTTTLQNISEDVLAVMDNKNPTIKQQTSLFI
  ARSFRHCTSSTLPKSLLKPFCAALLKHINDSAPEVRDAAFEALGTALKVVGEKSVNPFLA
  </code></pre>
  <p>The script that was used to find the motif is below, the problem now is that it does not show the position where the motif is found. Could you assist in how one could do so.</p>
  <pre><code>import re
  infile=open(&quot;seq.fasta&quot;,'r')
  out=open(&quot;results.csv&quot;,'w')
  pattern=re.compile(r&quot;(P[A-Z]{2}P)&quot;)
  for line in infile:
    line = line.strip(&quot;\n&quot;)
    if line.startswith('&gt;'):
       name=line
  else:      
     s = re.findall(pattern,line)
     print '%s:%s' %(name,s)
     out.write('%s:\t%s\n' %(name,s))
  </code></pre>
  <p>Their script seems to have worked because the desired output was</p>
  <pre><code>&gt;p1: 
  PGCP
  
  &gt;p1: 
  PHCP,
  PKCP
  </code></pre>
  <p>The problem with their script is that, it does not provide the position where the sequence was found. Could you please assist on how that script can be modified? I want to try it but I want my output to have (1) Name Of Sequence, (2) The Motif Found , (3) The Position</p>
  
Tags: <proteins><python><motifs><multi-fasta>
Title: finding motifs in fasta file with multiple sequences
ThreadText: # finding motifs in fasta file with multiple sequences
  
  (Asked by: username_0 on 2022-11-13)
  
  I am able to find matching motifs on a single sequence, as well as their position as shown below :
  
  ```
  demo = "ABCLXLYLZLABC"
  motif="L.L.L"
  for element in re.finditer(motif,demo):
      print(element.start(),element.end,element.group())
  
  ```
  
  This works and gives me the desired output which is:
   `3 8 LXLYL`
  
  Now I want to know how can I then do this same process but on a multifasta file.
  As done in this example script from <https://www.biostars.org/p/14305/> .
  
  The protein sequences on the file are :
  
  ```
  > P1
  MPPRRSIVEVKVLDVQKRRVPNKHYVYIIRVTWSSGATEAIYRRYSKFFDLQMQMLDKFP
  MEGGQKDPKQRIIPFLPGKILFRRSHIRDVAVKRLIPIDEYCKALIQLPPYISQCDEVLQ
  FFETRPEDLNPPKEEHIGKKKSGNDPTSVDPMVLEQYVVVADYQKQESSEISLSVGQVVD
  IIEKNESGWWFVSTAEEQGWVPATCLEGQDGVQDEFSLQPEEEEKYTVIYPYTARDQDEM
  NLERGAVVEVVQKNLEGWWKIRYQGKEGWAPASYLKKNSGEPLPPKLGPSSPAHSGALDL
  DGVSRHQNAMGREKELLNNQRDGRFEGRLVPDGDVKQRSPKMRQRPPPRRDMTIPRGLNL
  >P2
   MAEVRKFTKRLSKPGTAAELRQSVSEAVRGSVVLEKAKLVEPLDYENVITQRKTQIYSDP
   LRDLLMFPMEDISISVIGRQRRTVQSTVPEDAEKRAQSLFVKECIKTYSTDWHVVNYKYE
   DFSGDFRMLPCKSLRPEKIPNHVFEIDEDCEKDEDSSSLCSQKGGVIKQGWLHKANVNST
   ITVTMKVFKRRYFYLTQLPDGSYILNSYKDEKNSKESKGCIYLDACIDVVQCPKMRRHAF
   ELKMLDKYSHYLAAETEQEMEEWLIMLKKIIQINTDSLVQEKKDTVEAIQEEETSSQGKA
   ENIMASLERSMHPELMKYGRETEQLNKLSRGDGRQNLFSFDSEVQRLDFSGIEPDVKPFE
   EKCNKRFMVNCHDLTFNILGHIGDNAKGPPTNVEPFFINLALFDVKNNCKISADFHVDLN
   PPSVREMLWGTSTQLSNDGNAKGFSPESLIHGIAESQLCYIKQGIFSVTNPHPEIFLVVR
  >P3
  GDDSEWLKLPVDQKCEHKLWKARLSGYEEALKIFQKIKDEKSPEWSKYLGLIKKFVTDS
  NAVVQLKGLEAALVYVENAHVAGKTTGEVVSGVVSKVFNQPKAKAKELGIEICLMYVEIE
  KGESVQEELLKGLDNKNPKIIVACIETLRKALSEFGSKIISLKPIIKVLPKLFESRDKAV
  RDEAKLFAIEIYRWNRDAVKHTLQNINSVQLKELEEEWVKLPTGAPKPSRFLRSQQELEA
  KLEQQQSAGGDAEGGGDDGDEVPQVDAYELLDAVEILSKLPKDFYDKIEAKKWQERKEAL
  EAVEVLVKNPKLEAGDYADLVKALKKVVGKDTNVMLVALAAKCLTGLAVGLRKKFGQYAG
  HVVPTILEKFKEKKPQVVQALQEAIDAIFLTTTLQNISEDVLAVMDNKNPTIKQQTSLFI
  ARSFRHCTSSTLPKSLLKPFCAALLKHINDSAPEVRDAAFEALGTALKVVGEKSVNPFLA
  
  ```
  
  The script that was used to find the motif is below, the problem now is that it does not show the position where the motif is found. Could you assist in how one could do so.
  
  ```
  import re
  infile=open("seq.fasta",'r')
  out=open("results.csv",'w')
  pattern=re.compile(r"(P[A-Z]{2}P)")
  for line in infile:
    line = line.strip("\n")
    if line.startswith('>'):
       name=line
  else:      
     s = re.findall(pattern,line)
     print '%s:%s' %(name,s)
     out.write('%s:\t%s\n' %(name,s))
  
  ```
  
  Their script seems to have worked because the desired output was
  
  ```
  >p1: 
  PGCP
  
  >p1: 
  PHCP,
  PKCP
  
  ```
  
  The problem with their script is that, it does not provide the position where the sequence was found. Could you please assist on how that script can be modified? I want to try it but I want my output to have (1) Name Of Sequence, (2) The Motif Found , (3) The Position
  
  **Tags:** proteins, python, motifs, multi-fasta
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2022-11-13. Score: 0
  
  This is easy just replace `findall` with `finditer` in the above code. The index will then appear where the match first appears and where it stops. However, you will to parse the `finditer` object which in the code is `s`
  
  Then replace
  
  ```
  print '%s:%s' %(name,s)
  
  ```
  
  with
  
  ```
  for match_obj in s:
      # print each re.Match object
      print(match_obj)
      
      # extract each matching number
      print(match_obj.group())
  
  ```
  
  That should work. When it does you simply pass the `match_obj` and `match_obj.group()` to a file by replacing `s` with `match_obj, match_obj.group()`
  
  Thus replace
  
  ```
    out.write('%s:\t%s\n' %(name,s))
  
  ```
  
  with
  
  ```
    out.write('%s:\t%s\t%s\n' %(name,match_obj,match_obj.group()))
  
  ```
  
  You might need to do an append BTW.
  
  thus replace
  
  ```
  out=open("results.csv",'w')
  
  ```
  
  with
  
  ```
  import os
  if os.path.exists("results.csv"):
      os.unlink ("results.csv")
  out=open("results.csv",'a')
  
  ```
  
  > **Comments:**
  > **username_0**: Thank you so much for your suggestion, I am still new python user and will read up on biopython. With regards to the code will it now be: `else:s=re.finditer (pattern,line)`   `print'%s:%' %(name,s)`  ? Also by parse the finditer object what does that mean? I am struggling to link it to the original code. Could you perhaps try to edit your answer such that it looks like the original code, so that I can see where the changes will need to be made.  
  
  ---
  
  