pythonforbio.
[WASM idle]
Python Basics02/12

Strings

Starting sandbox…
Beginnerpuzzle3 tests

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:

  1. Remove leading and trailing whitespace.
  2. Remove any spaces inside the string.
  3. Convert to uppercase.
  4. Return "INVALID" if any character left is not A, C, G or T.

Otherwise return the cleaned sequence.

Test cases · 3

#viainputexpected stdout
1stdin atg gcc att ATGGCCATT
2stdinATGXCCINVALID
3stdinacgtACGT

Hints · 2

01Hint

Do the cleaning first, then validate what is left.

02Hint

set(sequence) <= set('ACGT') is true when every character is allowed.

starter

No output yet — run the code to populate this drawer.

Variables and TypesLists