14 Chapter 8, Strings: A Deeper Look
a. The re module’s split function tokenizes a string, using a regular expression
to specify the delimiter, and returns a list of strings.
b. The following code tokenizes a string by splitting it at any comma that’s fol-
lowed by 0 or more whitespace characters—\s is the whitespace character class
and * indicates zero or more occurrences of the preceding subexpression:
re.split(r‘,\s*’, ‘1, 2, 3,4, 5,6,7,8′)
c. The following code uses the keyword argument maxsplit to specify the maxi-
mum number of splits (in this case, after the 3 splits, the fourth string contains
the rest of the original string):
re.split(r‘,\s*’, ‘1, 2, 3,4, 5,6,7,8′, maxsplit=3)
d. All of the above statements are true.
8.12.3 Other Search Functions; Accessing Matches
8.12 Q9: Which of the following statements a), b) or c) is false?
a. The re module’s search function looks in a string for the first occurrence of a
substring that matches a regular expression and returns a match object (of type
SRE_Match) that contains the matching substring. The match object’s group
method returns that substring, as in the following session:
In [1]: import re
In [2]: result = re.search(‘Python’, ‘Python is fun’)
In [3]: result.group() if result else ‘not found’
Out[3]: ‘Python’
b. Function search returns None if the string does not contain the pattern.
c. You can search for a match only at the beginning of a string with function match.
d. All of the above statements are true.
8.12 Q10: Which of the following statements is false?
a. The re module’s findall function finds every matching substring in a string
and returns a list of the matching substrings.
b. The following code extracts all phone numbers of the form ###–###–####
from a string:
contact = ‘Wally White, Home: 555-555-1234, Work: 555-555-
4321′
re.findall(r‘\d{3}-\d{3}-\d{4}’, contact)