Replacing
Python · Unit 18: Regular expressions
- Full plan
- Python
- 10 exercises
re.sub(pattern, new, text) changes every match and gives back a new string.
It covers what .replace() can't: when the thing you're looking for isn't always the same.
import re
t = "tel 555-1234"
print(re.sub(r"\d", "*", t))Prints
tel ***-****
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Complete the code
Complete it so that it prints 345, with no spaces.
4. Predict the output
What does this code print?
5. Multiple choice
When is
re.suba better fit than the string's.replace()?6. Complete the code
Complete it so that only the first two digits change.
7. Find the bug
This program should print the text with no numbers in it. Which line has the error?
8. Find the case that fails
hide(t)should change every digit in the text into a*and leave the rest alone. Which call breaks it?9. Put the lines in order
Put the function in order. It leaves the text in lowercase and with no punctuation.
10. Predict the output
What does this code print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.