← All concepts

Lecture 2

Strings

A string is a sequence of characters — indexed and sliced like a list, with its own methods.

A sequence of characters

len(), indexing and slicing work just as they do for lists. in checks whether one piece of text appears inside another.

dna = "GATTACA"
print(len(dna), dna[0], dna[2:5], dna[-2:])
print("TTA" in dna)

Output

7 G TTA CA
True

Methods return a new string

Strings cannot be changed in place. .upper(), .replace() and friends hand back a new string — store it, or it is lost.

dna = "atgc"
dna.upper()
print(dna)
dna = dna.upper()
print(dna, dna.replace("T", "U"))

Output

atgc
ATGC AUGC

Useful methods

.count() counts a piece of text, .find() gives where it starts, .split() cuts text into a list and .strip() removes spaces and newlines at both ends.

line = " sample_07,GATTACA \n"
clean = line.strip()
print(clean.split(","))
print(clean.count("A"), clean.find("GAT"))

Output

['sample_07', 'GATTACA']
3 10

Going further

From the advanced notebook — this is what the advanced questions test.

Reversing, joining and searching

A step of -1 reverses. "-".join(list) glues strings together with a separator. .find() returns -1 when the text is not there, and .count() does not count overlapping matches.

print("ACGT"[::-1])
print("-".join(["ATG", "GCC", "TAA"]))
print("ATGC".find("X"), "AAAA".count("AA"))

Output

TGCA
ATG-GCC-TAA
-1 2