0
0
Pythonprogramming~20 mins

Searching and replacing text in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Text Replacement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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)
AI love oranges and apples are sweet.
BI love oranges and oranges are sweet.
CI love apples and oranges are sweet.
DI love apples and apples are sweet.
Attempts:
2 left
๐Ÿ’ก Hint
The replace method replaces only the first occurrence when count is 1.
โ“ Predict Output
intermediate
2: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)
ACall me at [phone] or 987-654-3210.
BCall me at 123-456-7890 or 987-654-3210.
CCall me at [phone] or [phone].
DCall me at 123-456-7890 or [phone].
Attempts:
2 left
๐Ÿ’ก Hint
re.sub replaces all matches by default.
โ“ Predict Output
advanced
2: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)
AThe dog scattered the catalog on the cathedral floor.
BThe dog sdogtered the dogalog on the doghedral floor.
CThe cat scattered the catalog on the cathedral floor.
DThe dog scattered the dogalog on the doghedral floor.
Attempts:
2 left
๐Ÿ’ก Hint
The \b in regex means word boundary.
โ“ Predict Output
advanced
2: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)
ANumbers: 2, 3, and 4.
BNumbers: 4, 9, and 16.
CNumbers: 4, 9, and 4.
DNumbers: 4, 3, and 16.
Attempts:
2 left
๐Ÿ’ก Hint
The function is called for each digit and returns its square as string.
๐Ÿง  Conceptual
expert
3: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)
Aba
Baaaa
Cbba
Dbb
Attempts:
2 left
๐Ÿ’ก Hint
re.sub does not replace overlapping matches.