This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Regular Expressions, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
What does re.search return when no match is found?
Answer: None
Why: A failed search returns None, so check the result before calling group().
What is the output?
import re
print(re.findall(r"\d", "a1b2"))Answer: ['1', '2']
Why: The pattern matches one digit at a time, and findall returns strings.
What does the pattern r"\d+" match?
Answer: One or more digits
Why: \d means a digit and + means one or more repetitions.
What does this code print?
import re
print(re.sub(r"cat", "dog", "cat cat"))Answer: dog dog
Why: re.sub replaces every occurrence of cat with dog.
Complete the import.
____ re
print(re.findall(r"\d+", "a1"))Answer: import
Why: The re module must be imported before its functions are used.
Complete the pattern that finds digit groups.
import re
text = "a1b22"
print(re.findall(r"____+", text))Answer: \d
Why: The pattern \d+ matches one or more digits.
Complete the replacement function.
import re
print(re.____(r"cat", "dog", "cat"))Answer: sub
Why: re.sub replaces matching parts of a string.
Complete the search call.
import re
print(re.____(r"\d+", "a1").group())Answer: search
Why: re.search returns the first match, and group() reads its text.
What does the program output?
import re
print(re.findall(r"\d+", "a1b22")[1])Answer: 22
Why: The matches are ['1', '22'], so index 1 is 22.
What appears on the screen?
import re
print(re.sub(r"\s+", "-", "a b"))Answer: a-b
Why: The repeated spaces become one hyphen, producing a-b.
What is printed?
import re
print(bool(re.search(r"\d", "abc")))Answer: False
Why: There is no digit in abc, so search returns None and bool(None) is False.
What is the output?
import re
print(re.findall(r"[A-Z]", "pyTHON"))Answer: ['T', 'H', 'O', 'N']
Why: The uppercase letters are T, H, O, and N.
Try the questions first
Open the practice page for Python Regular Expressions and answer the same 12 questions with instant feedback.