Strings hold text. In bioinformatics they hold sequences, identifiers and whole lines of a file, so string handling is most of the work.
Indexing and slicing
Indexing starts at 0. A slice s[start:stop] includes start and excludes
stop.
sequence = "ATGGCCATTGTA"
print(sequence[0])
print(sequence[-1])
print(sequence[0:3])
print(sequence[3:])
print(len(sequence))
Because stop is excluded, s[0:3] has exactly 3 characters. This is the same
rule BED files use, and the opposite of the 1-based inclusive rule used by GFF
and HGVS.
Common methods
Strings are immutable. Every method returns a new string.
raw = " atg gcc \n"
print(raw.strip())
print(raw.strip().upper())
print(raw.strip().replace(" ", ""))
print("ATGGCC".count("G"))
print("chr17:7676154".split(":"))
Building strings
Use an f-string to insert values into text.
gene = "TP53"
position = 7676154
print(f"{gene} at position {position:,}")
print(f"{0.5137:.2f}")
Use join to combine a list of strings.
codons = ["ATG", "GCC", "ATT"]
print("-".join(codons))
Task
Write clean_sequence(raw). It must:
- Remove leading and trailing whitespace.
- Remove any spaces inside the string.
- Convert to uppercase.
- Return
"INVALID"if any character left is not A, C, G or T.
Otherwise return the cleaned sequence.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | atg gcc att | ATGGCCATT |
| 2 | stdin | ATGXCC | INVALID |
| 3 | stdin | acgt | ACGT |
Hints · 2
01Hint
Do the cleaning first, then validate what is left.
02Hint
set(sequence) <= set('ACGT') is true when every character is allowed.