Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.5 (2 of 3): Cleaning and checking typed text

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Users type messy things

A user types " sAM " with extra spaces and strange capital (big) letters. Another types "16 years". A third types nothing.

Your program must clean and check what people type. Python has tools for text that make this easy.

Key words

WordWhat it meansExample
StringText inside quote marks."Sam"
MethodA function that belongs to a value. You write it after a dot.text.upper()
ConcatenationJoining strings together with +."Hi " + "Sam"
ValidationChecking that data makes sense before you use it.is the age only digits?
FunctionA named piece of code that does one job.len(text)
IndexThe position of a character. It starts at 0."Sam"[0] is "S"
InputData that goes into a program.what the user types

The cells students fill in are left blank in this preview.

Try it: change the text

Code: python
text = "  Hello World  "

print(text.strip())
print(text.upper())
print(text.lower())
print(len(text))
print(text.replace("World", "Leeds"))

# Change the text and run again.
# Each line gives a new string. The original stays the same.

Make a free account to save your work and track your progress.

The string tools you need

CodeWhat it doesExample result
`text.strip()`Remove spaces from both ends" hi " gives "hi"
`text.upper()`Make all letters capitals"hi" gives "HI"
`text.lower()`Make all letters small"Hi" gives "hi"
`text.split()`Break into a list of words"a b c" gives ["a", "b", "c"]
`text.replace("a", "b")`Swap one piece of text for another"cat" gives "cbt"
`text.find("a")`Find the index of a piece, or -1"cat" gives 1
`text.index("a")`Like find, but an error if missing"cat" gives 1
`len(text)`Count the characters"cat" gives 3
`text.count("a")`Count how many times a piece appears"banana" gives 3
`ord("A")`The number the computer uses for a letter65
`chr(65)`The letter for a number"A"

The cells students fill in are left blank in this preview.

The checking tools

CodeTrue when...Example
`text.isdigit()`Every character is a digit"123" is True, "12a" is False
`text.isalpha()`Every character is a letter"abc" is True, "ab1" is False
`text.isalnum()`Every character is a letter or digit"ab1" is True, "ab 1" is False
`text.isupper()`All the letters are capitals"HI" is True
`text.islower()`All the letters are small"hi" is True

The cells students fill in are left blank in this preview.

What does it give?

Have a go

What does it give?

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Match the tool to the problem

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Clean, check, then convert

flowchart TD
  s([Start]) --> i[/Input: age typed by the user/]
  i --> c[Clean: strip the spaces]
  c --> q{Is it only digits?}
  q -->|no| m[/Output: Please type a whole number/]
  m --> i
  q -->|yes| n[Convert with int]
  n --> e([End])

Clean, check, then convert

Tip

Always do three things in this order. Clean the text. Check it. Then convert it (change it to a number). This is how programs validate input.

Try it: clean, check, convert

Code: python
typed = "  16 "

clean = typed.strip()

if clean.isdigit():
    age = int(clean)
    print("Age next year:", age + 1)
else:
    print("Please type a whole number")

# Change typed to "sixteen" and run again.

Make a free account to save your work and track your progress.

Watch: clean, check, then convert

Press Play on the short film below. It cleans, checks and converts typed text, as the code above does, and shows why a method alone does not change a string.

Film: cleaning and checking typed text

Cleaning and checking typed text

Every scene, as text

  1. A user typed sAM with two spaces before it and one after, so typed holds 6 characters. clean = typed.strip() removes the spaces from both ends, so clean holds "sAM". print(len(typed), len(clean)) shows 6 3: len() counts the spaces too.
  2. upper() makes every letter a capital and lower() makes every letter small. With name = "sAM", big = name.upper() holds "SAM", only the s changing, and small = name.lower() holds "sam", the A and the M changing.
  3. Myth (false): a method changes the string it is used on. name.upper() gives a new string, "SAM", but nothing keeps it. The original stays the same, so print(name) still shows sAM.
  4. The cure is assignment: name = name.upper() puts the new string into name, so print(name) shows SAM.
  5. isdigit() is True when every character is a digit. print("16".isdigit()) shows True. print("16 years".isdigit()) shows False: the space and the letters are not digits. print("2.5".isdigit()) shows False: the . is not a digit.
  6. Clean, check, then convert. typed holds 16 with two spaces before it and one after. clean = typed.strip() holds "16", clean.isdigit() is True, and only then age = int(clean) changes it to the number 16, so print("Age next year:", age + 1) shows Age next year: 17, print() putting a space between its two items. This is validation: checking that data makes sense before you use it.

Your turn: six text tools

Write six functions that clean and check text. shout removes spaces from both ends and makes capitals. is_valid_age is True when the text is only digits. first_word gives the first word of a sentence. clean_phone takes every space out of a phone number. username_ok is True for letters and digits only, at least 4 characters long. next_letter gives the next letter of the alphabet, using ord() and chr(). Press Run Tests.

Code: python
def shout(text):
    # Remove spaces from both ends, then make every letter a capital.
    return None


def is_valid_age(text):
    # True if the text is only digits, such as "16". False for "sixteen" or "".
    return None


def first_word(text):
    # Give back the first word of a sentence. Words are split by spaces.
    return None


def clean_phone(text):
    # Take every space out of the text. "07700 900 123" becomes "07700900123".
    return None


def username_ok(name):
    # A good username has only letters and digits, and is at least 4 characters long.
    return None


def next_letter(letter):
    # A secret code: give back the next letter of the alphabet. "a" gives "b".
    # Use ord() to get the number of a letter and chr() to turn a number into a letter.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Remember

Important

Clean with strip, upper and lower. Split into words with split. Change with replace. Check with isdigit, isalpha and isalnum. ord() and chr() turn a letter into a number and back. Always clean, check, then convert.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.