Python Basics02/13
Starting sandbox…
Beginner·3 graded tests

Strings

A string is an immutable sequence of characters. Immutability means no operation modifies a string in place: every method that appears to change a string returns a new one, leaving the original unchanged. Strings are the primary data type in sequence analysis, where they hold nucleotide and amino acid sequences, identifiers, and individual lines of a file.

Indexing and slicing

Indexing is zero-based: s[0] is the first character. Negative indices count backwards from the end, so s[-1] is the last character.

A slice s[start:stop] includes the character at start and excludes the character at stop. This half-open convention means the length of a slice is stop - start, and that s[:n] and s[n:] partition the string with no overlap and no gap.

[1]python
out1ms
A A
ATG 3
True

The half-open convention is the same one used by the BED file format. GFF, VCF and HGVS instead use one-based inclusive coordinates. Converting between the two is a frequent source of off-by-one errors: a feature reported at positions 100–102 in GFF corresponds to sequence[99:102] in Python.

[2]python
out1ms
GCC

A slice accepts an optional third value, the step. s[::3] selects every third character, and s[::-1] reverses the string.

[3]python
out1ms
AGAG
ATGTTACCGGTA

Methods

String methods fall into three groups: those that clean (strip, replace), those that change case (upper, lower), and those that inspect (count, find, startswith). All return new values.

[4]python
out1ms
'  atg gcc  ' -> 'ATGGCC'
2 True

split divides a string into a list on a separator, and join combines a list of strings using the string it is called on as the separator. They are inverses, and together they handle most delimited-text parsing.

[5]python
out1ms
['chr17', '7676154', 'G', 'A']
chr17|7676154|G|A

Formatting

An f-string interpolates expressions into text. A format specifier after a colon controls presentation: :.2f fixes two decimal places, :, inserts thousands separators, and :.1% formats a fraction as a percentage.

[6]python
out1ms
TP53 at 7,676,154
GC content: 51.4%

Task

Write clean_sequence(raw). It must:

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

Otherwise return the cleaned sequence. Perform the cleaning before the validation, so that input containing only spaces and valid bases is accepted.

exerciseEvery submission runs independently in a fresh namespace.

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.