Advanced Sequence Operations
Beyond the basics (transcribe, translate, reverse complement), Seq supports frame-specific translation, restriction analysis, and simple statistics - the operations that come up constantly when preparing sequences for analysis.
Translating in Frames
from Bio.Seq import Seq
dna = Seq("ATGCGTACGTAA")
print(dna.translate()) # frame 0
print(dna.translate(table=11)) # bacterial table
print(dna.translate(to_stop=True)) # stop at first stop codon
# frames on a longer sequence:
long_dna = Seq("ATGGCTAGTACCGGTA")
for frame in range(3):
sub = long_dna[frame:]
prot = sub.translate(table=11, cds=False)
print(frame, str(prot))
CDS Translation
# cds=True assumes the sequence is a complete coding sequence
# (starts with a start codon, ends with a stop codon)
print(long_dna.translate(cds=True))
GC Content and Statistics
dna = Seq("ATGCGTACGTAACGG")
gc = (dna.count("G") + dna.count("C")) / len(dna)
print(f"GC: {gc:.2%}")
# codon usage quick view
from collections import Counter
codons = Counter(dna[i:i+3] for i in range(0, len(dna) - 2, 3))
print(codons.most_common(5))
Restriction Enzymes (Restriction module)
from Bio.Restriction import RestrictionEnvelope, complete
# list enzymes and find cut sites
from Bio import Restriction
enz = Restriction["EcoRI"]
seq = Seq("AATTGGCCATTAATT")
print(enz.search(seq)) # cut positions
Quality Trimming Concepts (FASTQ)
For NGS reads, common preprocessing is quality trimming: drop leading/trailing bases below a Phred threshold. Biopython exposes quality via letter_annotations["phred_quality"]; a simple trimmer:
def trim_qual(rec, q_min=20):
q = rec.letter_annotations.get("phred_quality", "")
if not q:
return rec
left, right = 0, len(q)
while left < right and q[left] < q_min:
left += 1
while right > left and q[right - 1] < q_min:
right -= 1
sliced = rec[left:right]
return sliced
# apply to each record from SeqIO.parse("reads.fastq", "fastq")
Summary
Advanced Seq operations include frame-specific and CDS-aware translation with genetic tables, GC-content and codon statistics, restriction enzyme site search via Bio.Restriction, and quality trimming of FASTQ records using phred_quality. These turn raw sequences into analysis-ready data.