Python for Biologists

Lesson 4 of 14 · 11 min

String Methods for Sequence Analysis

DNA is written as a chain of the letters A, T, G and C, which Python stores as a "string": text wrapped in quotation marks. A "variable" is simply a name that holds a value so we can reuse it, and every string comes with built-in "methods" — ready-made actions you run by typing a dot and the method's name. In this lesson we count bases, tidy up letter case, transcribe DNA to RNA, and locate a motif, printing each result with an f-string.

Tally And Clean The Sequence

The .count() method reports how many times a given letter appears, but it is case-sensitive, so it treats "A" and "a" as different characters. To avoid missing any bases we first standardize the text with .upper(), which returns a new copy in capitals (its partner .lower() gives all lower-case). We then read each tally into an f-string — a string written with an f before its opening quote, where a variable inside curly braces {} is swapped for its value.

python
dna = "atgCTtAGCgattac"
dna = dna.upper()
print(f"Clean sequence: {dna}")
print(f"A:{dna.count('A')}  T:{dna.count('T')}  G:{dna.count('G')}  C:{dna.count('C')}")
Clean sequence: ATGCTTAGCGATTAC
A:4  T:5  G:3  C:3

Transcribe And Locate A Motif

Transcription is the cell copying DNA into RNA, and RNA uses uracil (U) everywhere DNA uses thymine (T). The .replace("T", "U") method swaps every T for a U and returns the RNA string, leaving the DNA variable unchanged. A motif is a short, meaningful run of bases, and .find() reports the index where a motif first appears — counting the first character as position 0 — or -1 when it is missing.

python
rna = dna.replace("T", "U")
print(f"DNA: {dna}")
print(f"RNA: {rna}")
DNA: ATGCTTAGCGATTAC
RNA: AUGCUUAGCGAUUAC
python
motif = "GATTAC"
position = dna.find(motif)
print(f"Motif {motif} starts at index {position}")
print(f"Motif TTTT found at: {dna.find('TTTT')}")
Motif GATTAC starts at index 9
Motif TTTT found at: -1

Try it yourself: Store the sequence "TTACGGATCC" in a variable, uppercase it, and print its G and C counts with an f-string. Then, on that same DNA variable, run .find("GGATCC") to locate the BamHI restriction site — what index do you get, and what does .find("AAAA") return? Finally, transcribe the DNA to RNA with .replace("T", "U") and print the result.