Sequences are stored in FASTA files. A header line starts with > and gives the name, its first word. The lines after it hold the sequence, often split over several lines, as in this file of one DNA sequence written 5' to 3':
>geneA sample 1
ATGCGC
GTAA
Your program must join those lines before measuring anything.
GC CONTENT
GC%=nA+nC+nG+nTnG+nC×100
Holds for a DNA sequence written in capitals ACGT. nX is the number of bases X; the result is in per cent. Letters other than A, C, G and T, such as N (an unknown base), are left out of the denominator.
The full program, in plain Python 3 with no extra packages. It assumes each header carries a different name.
def read_fasta(path):
seqs, name = {}, None
with open(path) as f:
for line in f:
line = line.strip()
if line.startswith(">"):
name = line[1:].split()[0]
seqs[name] = []
elif name and line:
seqs[name].append(line.upper())
return {n: "".join(p) for n, p in seqs.items()}
def gc_content(seq):
gc = seq.count("G") + seq.count("C")
acgt = gc + seq.count("A") + seq.count("T")
return 100 * gc / acgt if acgt else 0.0
for name, seq in read_fasta("genes.fasta").items():
print(name, len(seq), round(gc_content(seq), 1))
A header opens a new entry and each sequence line is appended to it, so many-line sequences are joined. len(seq) counts every letter, while gc_content divides by the count of A, C, G and T, as the formula does. Biopython is a separate package (install it with pip install biopython; version 1.80 or later). Its parser does the reading, so the same task is shorter:
from Bio import SeqIO
from Bio.SeqUtils import gc_fraction
for rec in SeqIO.parse("genes.fasta", "fasta"):
print(rec.id, len(rec.seq), round(100 * gc_fraction(rec.seq), 1))
The two programs agree on sequences of A, C, G and T. Biopython also counts some other letters, such as S (G or C), so results can differ when those occur.