Hone

Lessons · Python · cleaning and reshaping text

Cleaning and reshaping text

Strings come with methods: strip, lower, split, replace, startswith. They return new strings; the original never changes.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Real input is messy: spaces, mixed case, odd punctuation. Every parser, search and validator starts by normalising text with these.

How to think about it

What should the text look like before I compare it? Ask what the text should look like before you compare or split it. Then chain: text.strip().lower(). Read the chain left to right as steps.

Worked example

raw = "  Hello, World  "
Padding and case we do not want.
clean = raw.strip().lower()
"hello, world". Two steps, one line.
words = clean.replace(",", "").split()
["hello", "world"]: remove the comma, split on whitespace.
print(clean.startswith("hello"))
True.

Your turn

Normalise an email address for comparison.

key = email.().lower()

The trap

Forgetting that methods return a new string: s.strip() alone does nothing. s = s.strip().

Practise cleaning and reshaping text on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.