Hint: Use replace(old, new) without extra keywords [OK]
Common Mistakes:
Using arrows or keywords inside replace()
Adding unsupported parameters like all=True
Confusing parameter order
3. What will be the output of this code?
text = 'apple apple apple'
new_text = text.replace('apple', 'orange', 2)
print(new_text)
medium
A. 'apple orange orange'
B. 'orange orange orange'
C. 'orange orange apple'
D. 'apple apple orange'
Solution
Step 1: Understand replace with count
The third argument 2 limits replacements to first two occurrences.
Step 2: Apply replacements
First two 'apple' become 'orange', last remains 'apple'. Result: 'orange orange apple'.
Final Answer:
'orange orange apple' -> Option C
Quick Check:
replace with count=2 changes first two only [OK]
Hint: Count limits how many replacements happen [OK]
Common Mistakes:
Replacing all occurrences ignoring count
Replacing from the end instead of start
Miscounting number of replacements
4. The following code tries to replace 'blue' with 'red' but causes an error. What is the error?
text = 'blue sky'
text.replace('blue', 'red', 'all')
print(text)
medium
A. SyntaxError due to wrong quotes
B. AttributeError because replace is not a string method
C. No error, prints 'red sky'
D. TypeError because 'all' is not an integer for count
Solution
Step 1: Check replace() parameters
The third parameter must be an integer count, but 'all' is a string.
Step 2: Identify error type
Passing a string instead of int causes a TypeError at runtime.
Final Answer:
TypeError because 'all' is not an integer for count -> Option D
Quick Check:
replace count must be int, not string [OK]
Hint: Count parameter must be integer, not string [OK]
Common Mistakes:
Using strings instead of integers for count
Expecting replace to modify original string
Confusing error types
5. You have a paragraph stored in text. You want to replace only the first 3 occurrences of the word 'error' with 'issue'. Which code snippet correctly does this?
hard
A. new_text = text.replace('error', 'issue', 3)
B. new_text = text.replace('error', 'issue', count=3)
C. new_text = text.replace('error', 'issue', '3')
D. new_text = text.replace('error', 'issue')[:3]
Solution
Step 1: Use replace with count parameter
To replace only first 3 occurrences, use replace(old, new, count) with count=3.