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.
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.
GCC
A slice accepts an optional third value, the step. s[::3] selects every third
character, and s[::-1] reverses the string.
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.
' 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.
['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.
TP53 at 7,676,154 GC content: 51.4%
Task
Write clean_sequence(raw). It must:
- Remove leading and trailing whitespace.
- Remove any spaces inside the string.
- Convert the result to uppercase.
- 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.
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.