0
0
Pythonprogramming~5 mins

Searching and replacing text in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Astr.split(separator)
Bstr.replace(old, new)
Cstr.index(substring)
Dstr.find(substring)
What does str.find(substring) return if the substring is not found?
A-1
B0
CNone
DRaises an error
How can you replace only the first occurrence of a substring in Python?
AUse <code>str.split()</code>
BUse <code>str.replace(old, new)</code>
CUse <code>str.find()</code>
DUse <code>str.replace(old, new, 1)</code>
Which Python module provides advanced searching and replacing with patterns?
Are
Bos
Csys
Dmath
What will this code print?
text = 'cat dog cat'
print(text.replace('cat', 'fox', 1))
Acat dog fox
Bfox dog fox
Cfox dog cat
Dcat dog cat
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.