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
| Word | What it means | Example |
|---|---|---|
| String | Text inside quote marks. | "Sam" |
| Method | A function that belongs to a value. You write it after a dot. | text.upper() |
| Concatenation | Joining strings together with +. | "Hi " + "Sam" |
| Validation | Checking that data makes sense before you use it. | is the age only digits? |
| Function | A named piece of code that does one job. | len(text) |
| Index | The position of a character. It starts at 0. | "Sam"[0] is "S" |
| Input | Data 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
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.
The string tools you need
| Code | What it does | Example 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 letter | 65 |
| `chr(65)` | The letter for a number | "A" |
The cells students fill in are left blank in this preview.
The checking tools
| Code | True 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 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
The safe order
data-callouts.tip.label
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.