This lesson introduces almost nothing new. It gives you five small tasks that use what the last four lessons taught: methods, indexing and slicing, and f-strings. Try each one on your own before reading the solution. Write the first version badly if you must. A messy solution you wrote yourself teaches more than a tidy one you only read.
Task 1: tidy a name
A signup form lets people type their name any way they like. We want " mAYA rao " to become "Maya Rao". The three steps are: split into words, which also removes the stray spaces, capitalise each word, and join with a single space.
raw = " mAYA rao "
words = raw.split()
print(words)
fixed = " ".join(word.capitalize() for word in words)
print(fixed)['mAYA', 'rao']
Maya RaoThe split() with no argument ignores extra spaces, and capitalize() lowercases the rest of each word, which fixes the odd mAYA. The expression inside join is a generator expression, a compact loop you will learn about later. A full loop works equally well.
raw = " mAYA rao "
result = ""
for word in raw.split():
if result:
result += " "
result += word.capitalize()
print(result)Maya RaoTask 2: count the words and the longest word
Given a sentence, report how many words it has and which one is the longest.
sentence = "The library opens early on Saturday mornings"
words = sentence.split()
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
print(f"Words: {len(words)}")
print(f"Longest: {longest} ({len(longest)} letters)")Words: 7
Longest: Saturday (8 letters)The loop keeps the best word seen so far and replaces it when something longer appears. This "keep the best so far" pattern is worth remembering. It works for biggest numbers, lowest prices and many other jobs.
Task 3: count the vowels
Count how many vowels a sentence has. Lowercase first so you only need to test five letters.
text = "Green Leaf Books Opens At Nine"
vowels = "aeiou"
count = 0
for letter in text.lower():
if letter in vowels:
count += 1
print(f"{count} vowels in {len(text)} characters")11 vowels in 30 charactersThe check letter in vowels asks whether the single character appears anywhere in the string "aeiou". Because the text was lowercased, the capital O and A are handled by the same comparison as their lowercase forms.
Task 4: is it a palindrome
A palindrome reads the same forwards and backwards, ignoring case, spaces and punctuation. Write a check that accepts "Race car" and rejects "Green Leaf". Clean the text first, then compare it with its reverse using the slice from the previous lesson.
def clean(text):
kept = ""
for ch in text.lower():
if ch.isalnum():
kept += ch
return kept
for phrase in ("Race car", "Was it a car or a cat I saw?", "Green Leaf"):
cleaned = clean(phrase)
print(f"{phrase!r}: {cleaned == cleaned[::-1]}")'Race car': True
'Was it a car or a cat I saw?': True
'Green Leaf': FalseThe function clean keeps only letters and digits, which strips spaces and punctuation in one go. Functions are covered properly later in the course, so for now read it as a named, reusable block. The !r after the name in the f-string prints the text with its quotes.
Task 5: mask a card number
A shop receipt should never show a full card number. Show only the last four digits and replace the rest with stars. This task is all about slices and repetition.
number = "4111222233334444"
masked = "*" * (len(number) - 4) + number[-4:]
print(masked)
groups = [masked[i:i + 4] for i in range(0, len(masked), 4)]
print(" ".join(groups))************4444
**** **** **** 4444The number used here is made up. Never put a real card number in code. The second part cuts the string into groups of four. It uses a list comprehension, which you will meet in the collections section. The range function steps through the positions 0, 4, 8 and 12.
How to approach a text problem
All five solutions followed the same plan, which you can reuse.
- Write down one example of the input and the exact output you want.
- Clean the input first. Strip, lowercase and remove what you do not need.
- Break it into pieces with
split(), or work on single characters with a loop. - Build the answer step by step, printing in between while you work.
- Test with an awkward example such as an empty string, extra spaces or capitals.
Where to go next
Once these five tasks feel comfortable, make up variations of your own. Count only the consonants. Find the shortest word instead of the longest. Reject a phrase that has no letters at all. Turn "first last" into "Last, First". Each variation forces you to think about the plan rather than copy a pattern, and that is the skill that matters. After this section, the collections lessons give you lists and dictionaries, which make many of these tasks shorter and let you count how often every word appears in a text.
Common mistakes
- Comparing before cleaning.
"Race car"does not equal its reverse until you lowercase it and remove the space. - Splitting on a single space.
"a b".split(" ")contains an empty piece. Plainsplit()avoids that. - Forgetting an empty string.
words[0]fails when the sentence has no words. Check the length first if the input can be empty. - Modifying a string inside a loop and expecting the original to change. Build a new string, as
resultdoes above. - Counting with
==on a whole string when you wanted one character at a time. Loop over the characters.
A video version of this topic is in the video course at /learn/python/.
Exercise
Write code that takes the text " the QUICK brown fox ", and prints three lines: the cleaned text in title case, the number of words, and the text with the first letter of each word taken to make an acronym in capitals (TQBF).
Show a possible answer
text = " the QUICK brown fox "
words = text.split()
print(" ".join(words).title())
print(len(words))
acronym = ""
for word in words:
acronym += word[0].upper()
print(acronym)The Quick Brown Fox
4
TQBFKey points
- Real text jobs combine several small tools: strip and lower to clean, split to break apart, a loop to inspect, and an f-string to report.
- Solve a problem in steps. Print each stage while you work, then remove the extra prints.
- Normalise text, for example by lowercasing and removing spaces, before you compare or count it.
- Slices handle fixed-position jobs such as masking all but the last four digits.
- Build output with a running string or a list and join. Do not try to change a string in place.