# How to read and edit a FASTA file with python using regular expression?

I have a file containing protein sequence information of 100 odd proteins. Each sequence starts with a header that looks like this:

>sp|Q9UDW1|QCR9_HUMAN Cytochrome b-c1 complex subunit 9 OS=Homo sapiens OX=9606 GN=UQCR10 PE=1 SV=3


I want to edit these header to look like this:

>Q9UDW1


I have tried the following code:

import re
with open ('WT.fasta', 'r+') as f:
for i in range(len(contents)-1):
target = re.compile(r'>..\|(.*)\|.*', contents[i])
target.sub(r'\1', contents[i])


I think I am not being able to call the right methods to do this. I have been trying to read the documentation: https://docs.python.org/3/library/re.html. I am not been able to understand it and feeling overwhelmed by the details. I would really appreciate if anyone could help or point me in the right direction. Thanks!

• Do you absolutely need to use python? A simple sed would do this much faster. Aug 10 at 16:16
• Hi @RamRS, I am actually very new to bioinformatics. I still have not learnt about sed or awk commands :-)
– Noob
Aug 11 at 4:35
• You definitely should - these will save you a lot of time for tasks that are too small in get Python/R involved. Aug 11 at 15:24
• @RamRS, I would love learn about them. Would you have any suggestions about any course, or tutorials on these topics?
– Noob
Aug 11 at 19:03
• Just google around. The way to learn these would be using them on copies of files for tasks like your current question - start there and you'll find more and more places you can use them. Aug 12 at 14:04

In general, I usually recommend Biopython for any sort of fasta parsing, but the code below should work as well.

with open ('WT.fasta', 'r+') as in_f, open("WT_out.fasta", 'w') as out_f:
for line in in_f:
if line[0] == ">":
out_f.write(">" + line.split('|')[1] + "\n")
else:
out_f.write(line)

• Hi, The code executes, does not show any error messages. But the file looks the same as before!
– Noob
Aug 11 at 4:29
• @Noob which file are you looking at? The code creates a new file WT_out.fasta Aug 11 at 4:30
• Oh sorry! My bad :/... I am an absolute idiot!
– Noob
Aug 11 at 4:33

You could do this with awk by processing the header:

$awk -v FS="|" '{ if ($0 ~ /^>/) { printf(">%s\n", $2) } else print$0 }' in.fa > out.fa


For example:

% echo -e ">sp|Q9UDW1|QCR9_HUMAN Cytochrome b-c1 complex subunit 9 OS=Homo sapiens OX=9606 GN=UQCR10 PE=1 SV=3\nACCGT" | awk -v FS="|" '{ if ($0 ~ /^>/) { printf(">%s\n",$2) } else print \$0 }'
>Q9UDW1
ACCGT

• Hi @AlexReynolds, Thanks a lot! I will try it.
– Noob
Aug 11 at 4:36