Sequence analysis: measuring DNA with code
Once DNA is a string, you can measure it. Counting bases and computing GC content are the first tools of bioinformatics — and they're a few lines of Python.
The big idea
Sequence analysis uses string operations to measure a sequence — counting bases, computing GC content, comparing strands.
See it in code
Measuring a strand starts with counting. len gives its size, and .count() tallies how many times a single base appears:
dna = "ATGGCGCGCTTAA"
print("Length:", len(dna))
print("G count:", dna.count("G"))
print("C count:", dna.count("C"))Length: 13 G count: 4 C count: 3
dna.count("G") scans the whole strand for you. These raw counts are the raw material for every measurement that follows.
Counts become insight once you turn them into a ratio. Add the G and C counts, divide by the length, and you have the fraction of the strand that's G or C:
dna = "ATGGCGCGCTTAA"
gc = dna.count("G") + dna.count("C")
fraction = gc / len(dna)
print("G + C:", gc, "out of", len(dna))
print("GC fraction:", round(fraction, 2))G + C: 7 out of 13 GC fraction: 0.54
gc / len(dna) is the whole idea behind GC content. Next we report it the way biologists do — as a percent.
Now all four counts together, and GC content — the fraction of G and C — formatted as the percent biologists actually report, because GC-rich regions bind more tightly:
dna = "ATGGCGCGCTTAA"
a = dna.count("A")
g = dna.count("G")
c = dna.count("C")
t = dna.count("T")
gc_content = (g + c) / len(dna) * 100
print("Counts -> A:", a, "T:", t, "G:", g, "C:", c)
print(f"GC content: {gc_content:.1f}%")Counts -> A: 3 T: 3 G: 4 C: 3 GC content: 53.8%
.count and a little arithmetic turned raw sequence into a meaningful statistic. Real genomes are billions of bases long, but the code is identical — that's the power of measuring data instead of eyeballing it.
Counting and computing ratios over a sequence is a universal analysis move: word frequencies in a document, error rates in a log, the share of a category in a dataset. Bioinformatics scales it up — the same count and percentage over a whole chromosome.
Try it yourself
Compute AT content and confirm it plus GC content equals 100%. Then write a gc(dna) function and run it on several strands to compare which is GC-rich.
The common mistake
Dividing by the wrong total, or forgetting sequences can contain unexpected letters (like N for 'unknown'). Always divide by len(dna), and be ready for real data that isn't a clean four-letter string.
What it unlocks
Analysis builds on string methods, operators, and f-strings, and extends to comparing orthologs across species.