Python for Biologists

Lesson 3 of 14 · 10 min

Strings: Treating DNA as Text

A DNA sequence is just a run of the letters A, T, C, and G, so we can store it in Python as a string. A string is any piece of text wrapped in quotation marks. Once the sequence is a string, Python gives us simple ways to measure it and to cut pieces out of it.

DNA as a string

python
seq = "ATGCGTACGTTAG"   # store the DNA sequence as text (a string)
print(seq)               # show the whole sequence
print(len(seq))          # len() counts how many letters (bases) there are
ATGCGTACGTTAG
13

Picking single bases

Every base sits at a numbered position, and Python starts counting at 0, not 1. So seq[0] is the first base and seq[1] is the second base. Writing a negative number counts backward from the end, so seq[-1] is the last base.

python
print(seq[0])   # first base (positions start at 0)
print(seq[-1])  # last base (negative numbers count from the end)
A
G

Slicing out codons

python
print(seq[0:3])   # first codon: positions 0, 1, 2 (position 3 is excluded)
print(seq[3:])    # from position 3 to the end (drops the first codon)
print(seq[::-1])  # the sequence reversed as text (NOT the reverse complement)
ATG
CGTACGTTAG
GATTGCATGCGTA

Try it yourself: Using seq = "ATGCGTACGTTAG", print len(seq), then print the second base with seq[1] and the last three bases with seq[-3:]. Finally pull out the second codon with seq[3:6] and confirm it prints CGT.