Python course · Part 6: Text · lab 6 of 7
Working with text
Cleaning what people type, splitting a line into fields and putting it back together, checking what text contains, and building slugs and references that are safe to put in a URL.
By the end you can
- Clean and normalise text that came from a person
- Split a line into fields and join fields back into a line
- Check what text starts with, ends with or contains, without crashing
- Turn a title into a slug and build a reference people can read out
Easier if you did first
step 1 of 4
Cleaning what people type
Anything a person types arrives untidy. Leading spaces from a paste, capital letters from a phone keyboard, a stray space in the middle of a phone number. Cleaning it is not optional, and doing it in one place is what keeps the rest of the program simple.
The usual pass: .strip() removes spaces from both ends, .lower() flattens the case so comparisons work, .replace(a, b) swaps one thing for another.
Comparing email addresses is the classic example. "Ama@Example.COM " and "ama@example.com" are the same address to everybody except your database, unless you normalise first.
Remember that text cannot be changed in place. Every one of these methods returns new text, so you have to keep what comes back.
Write the three.
" Ama@Example.COM ".strip().lower() # "ama@example.com"
"024 123 4567".replace(" ", "") # "0241234567"
"a-b-c".replace("-", "") # "abc"What these words mean
- .strip()
- Removes whitespace from both ends.
- .lower() / .upper()
- Flattens the case.
- .replace(a, b)
- Swaps every a for b.
- .isdigit()
- True when the text is all digits.
- immutable
- Text never changes; methods return new text.
Easy to get wrong
Comparing emails without normalising
Normalising on the way in, once
Someone signs up as "Ama@Example.com" and signs in as "ama@example.com". Both are the same address to every mail server on earth, and two different rows in your database.
text.strip() with no assignment
text = text.strip()
The method returns new text and leaves the original alone, so without assigning it the call does nothing at all and the bug looks like the method is broken.
What we check
- Spaces and capitals are dealt with
- Clean input is left alone
- Only the digits survive, in order
- No digits gives empty text, not an error
- Brackets and plus signs go too
- A real address passes, even untidy
- Text with no @ fails
- Two @ signs fail
- A missing name or a missing dot fails
Nothing printed yet. Run your code.