Challenge - 5 Problems
Text Replacement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of simple string replace
What is the output of this Python code?
Python
text = "I love apples and apples are sweet." result = text.replace("apples", "oranges", 1) print(result)
Attempts:
2 left
๐ก Hint
The replace method replaces only the first occurrence when count is 1.
โ Incorrect
The replace method replaces the first 'apples' with 'oranges'. The second 'apples' remains unchanged.
โ Predict Output
intermediate2:00remaining
Replacing with regex pattern
What is the output of this code using regex substitution?
Python
import re text = "Call me at 123-456-7890 or 987-654-3210." result = re.sub(r"\d{3}-\d{3}-\d{4}", "[phone]", text) print(result)
Attempts:
2 left
๐ก Hint
re.sub replaces all matches by default.
โ Incorrect
The regex matches both phone numbers and replaces them with '[phone]'.
โ Predict Output
advanced2:00remaining
Replacing only whole words
What is the output of this code that replaces only whole word 'cat' with 'dog'?
Python
import re text = "The cat scattered the catalog on the cathedral floor." result = re.sub(r"\bcat\b", "dog", text) print(result)
Attempts:
2 left
๐ก Hint
The \b in regex means word boundary.
โ Incorrect
Only the exact word 'cat' is replaced, not parts of other words.
โ Predict Output
advanced2:00remaining
Replacing with a function in re.sub
What is the output of this code that replaces digits with their squares?
Python
import re text = "Numbers: 2, 3, and 4." def square(match): num = int(match.group()) return str(num * num) result = re.sub(r"\d", square, text) print(result)
Attempts:
2 left
๐ก Hint
The function is called for each digit and returns its square as string.
โ Incorrect
Each digit is replaced by its square: 2->4, 3->9, 4->16.
๐ง Conceptual
expert3:00remaining
Effect of overlapping patterns in re.sub
Given the code below, what is the output?
Python
import re text = "aaaa" result = re.sub(r"aa", "b", text) print(result)
Attempts:
2 left
๐ก Hint
re.sub does not replace overlapping matches.
โ Incorrect
The pattern 'aa' matches twice non-overlapping: positions 0-1 and 2-3, replaced by 'b' each time, resulting in 'bb'.