Recall & Review
beginner
What Python method is commonly used to replace parts of a string?
The
str.replace(old, new) method is used to replace occurrences of old substring with new substring in a string.Click to reveal answer
beginner
How do you search for a substring inside a string in Python?
You can use the
in keyword or the str.find() method. in returns True or False, while find() returns the index or -1 if not found.Click to reveal answer
intermediate
What does
str.replace('a', 'b', 1) do?It replaces only the first occurrence of 'a' with 'b' in the string. The third argument limits the number of replacements.
Click to reveal answer
intermediate
Why might you use the
re.sub() function instead of str.replace()?re.sub() allows replacing text using patterns (regular expressions), which is more powerful for complex searching and replacing.Click to reveal answer
beginner
What will this code output?
text = 'apple apple apple'
print(text.replace('apple', 'orange', 2))It will output:
orange orange apple because only the first two 'apple' words are replaced.Click to reveal answer
Which method replaces all occurrences of a substring in Python?
✗ Incorrect
str.replace() replaces all occurrences of old with new.What does
str.find(substring) return if the substring is not found?✗ Incorrect
str.find() returns -1 if the substring is not found.How can you replace only the first occurrence of a substring in Python?
✗ Incorrect
The third argument in
str.replace() limits the number of replacements.Which Python module provides advanced searching and replacing with patterns?
✗ Incorrect
The
re module supports regular expressions for pattern matching.What will this code print?
text = 'cat dog cat'
print(text.replace('cat', 'fox', 1))✗ Incorrect
Only the first 'cat' is replaced with 'fox'.
Explain how to search for a substring and replace it in a Python string.
Think about how to check if text exists and then how to change it.
You got /4 concepts.
Describe when and why you would use the
re.sub() function instead of str.replace().Consider cases where simple text replacement is not enough.
You got /4 concepts.