Learning LibraryCore Coding LibraryTeens

String Methods in Python: clean, transform, and chain

Raw text is messy — stray spaces, wrong case, no structure. String methods clean and reshape it, and they chain, so one line can do several fixes at once.

The big idea

String methods return transformed copies of a string; because each returns a string, you can chain them left to right.

See it in code

1The basics

A string method returns a transformed copy. A DNA read arrives lowercase, and .upper() normalizes the case:

python
raw = "augggcuuu"
print(raw.upper())
Run it — the strand, uppercased:
AUGGGCUUU

.upper() handed back a new, uppercased string. raw itself is untouched — methods copy, they don't edit.

2A step further

Because each method returns a string, you can chain them. This read is also padded with spaces; .strip().upper() runs both fixes left to right in one line:

python
raw = "  augggcuuu  "
print(raw.strip().upper())
Run it — trimmed, then uppercased, in one pass:
AUGGGCUUU

.strip() runs first and hands its result to .upper(). Now let's chain it, then slice the clean strand into codons.

3In our world

The full pipeline: a padded, lowercase DNA sequence, cleaned with .strip().upper(), then sliced into three-letter codons:

python
raw = "  augggcuuu  "

dna = raw.strip().upper()
print(dna)

codons = [dna[i:i+3] for i in range(0, len(dna), 3)]
print(codons)
Run it — cleaned, then split into codons:
AUGGGCUUU
['AUG', 'GGC', 'UUU']

raw.strip().upper() reads left to right: strip first, then uppercase the result — the exact chain from the warm-up. Slicing with dna[i:i+3] grabs three characters at a time. For delimited text, .split(",") breaks a string into a list on each comma.

The same idea, everywhere

Cleaning and reshaping text is universal: normalize user input, parse a CSV row with .split(","), check a URL with .startswith("https"), count with .count("A"). Because methods return new strings, the original stays untouched — handy, and the source of one common bug (below).

Try it yourself

Count the guanine bases with dna.count("G"). Then parse a record: "Blaze,100,north".split(",") returns a list you can index. Chain three methods and read the order carefully.

The common mistake

Assuming a method edits in place. dna.upper() returns a new string and leaves dna unchanged — dna.strip() on its own line does nothing useful unless you reassign: dna = dna.strip(). Strings are immutable; methods always hand back a copy.

What it unlocks

Text tooling supports data types and f-strings, and drives the sequence analysis at the core of the biotech course.

Want the simpler version? Read the Kids version →