Chapter 8, Strings: A Deeper Look 1
Strings: A Deeper Look
8.1 Introduction
8.1 Q1: Which of the following statements a), b) or c) is false?
a. Strings support many of the same sequence operations as sets, lists and tuples.
b. Strings, like tuples, are immutable.
c. The re module can be used to match patterns in text.
d. All of the above statements are true.
8.2 Formatting Strings
8.2.1 Presentation Types
8.2 Q1: Which of the following statements is false?
a. The following f-string formats the float value 17.489 rounded to the hun-
dredths position:
f‘{17.489:.2f}‘
b. Python supports precision only for floating-point and Decimal values.
c. Formatting is type dependent—if you try to use .2f to format a string like
‘hello’, a NameError occurs.
d. The presentation type f in the format specifier .2f is required.
8.2 Q2: Which of the following statements is false?
a. The d presentation type in the following f-string formats strings as integer val-
ues:
f‘{10:d}‘
b. The integer presentation types b, o and x or X format integers using the binary,
octal or hexadecimal number systems, respectively.
c. The c presentation type in the following f-string formats an integer character
code as the corresponding character:
f‘{65:c} {97:c}‘
d. If you do not specify a presentation type, as in the second placeholder below,
non-string values like the integer 7 are converted to strings:
2 Chapter 8, Strings: A Deeper Look
f‘{“hello”:s} {7}‘
8.2 Q3: Which of the following statements a), b) or c) is false?
a. For extremely large and small values of floating-point and Decimal types, ex-
ponential (scientific) notation can be used to format the values more compactly.
b. The following interactive session shows the difference between f and e for a
large value, each with three digits of precision to the right of the decimal point:
In [1]: from decimal import Decimal
In [2]: f‘{Decimal(“10000000000000000000000000.0″):.3f}‘
Out[2]: ‘10000000000000000000000000.000′
In [3]: f‘{Decimal(“10000000000000000000000000.0″):.3e}‘
Out[3]: ‘1.000e+25’
c. For the e presentation type in snippet [3] of Part (c), the formatted value
1.000e+25 is equivalent to 1.000 x 1025. If you prefer a capital E for the exponent,
use the E presentation type rather than e.
d. All of the above statements are true.
8.2.2 Field Widths and Alignment
8.2 Q4: Which of the following statements is false?
a. By default, the following f-strings right-align the numeric values 27 and 3.5
and left-align the string “hello”:
f‘[{27:10d}]’
f‘[{3.5:10f}]’
f‘[{“hello”:10}]’
b. Python formats float values with six digits of precision to the right of the dec-
imal point by default.
c. For formatted values that have fewer characters than the field width, the re-
maining character positions are filled with spaces.
d. Formatted values with more characters than the field width cause a ValueEr-
ror.
4 Chapter 8, Strings: A Deeper Look
c. The following code formats the float value 17.489 rounded to the hundredths
position:
‘{:.3f}‘.format(17.489)
d. All of the above statements are true.
8.2 Q8: Which of the following statements a), b) or c) is false?
a. A format string may contain multiple placeholders, in which case the format
method’s arguments correspond to the placeholders from left to right:
‘{} {}‘.format(‘Amanda’, ‘Cyan’)
b. The format string can reference specific arguments by their position in the
format method’s argument list, starting with position 0, as in:
‘{0} {0} {1}‘.format(‘Happy’, ‘Birthday’)
You can reference each argument as often as you like and in any order.
c. You can reference keyword arguments by their keys in the placeholders, as in:
‘{first} {last}‘.format(first=‘Amanda’, last=‘Gray’)
‘{last} {first}‘.format(first=‘Amanda’, last=‘Gray’)
d. All of the above statements are true.
8.3 Concatenating and Repeating Strings
8.3 Q1: Consider the following code:
In [1]: s1 = ‘happy’
In [2]: s2 = ‘birthday’
In [3]: s1 += ‘ ‘ + s2
In [4]: s1
Out[4]: ‘happy birthday’
In [5]: symbol = ‘>’
In [6]: symbol *= 5
Chapter 8, Strings: A Deeper Look 5
In [7]: symbol
Out[7]: ‘>>>>>’
Which snippet(s) in this interactive session appear to modify existing strings, but
actually create new string objects?
a. Only snippet [3].
b. Only snippet [5].
c. Both snippets [5] and [6].
d. Both snippets [3] and [6].
8.4 Stripping Whitespace from Strings
8.4 Q1: Based on the string
sentence = ‘\t \n This is a test string. \t\t \n’
which of the following statements is false?
a. There are several string methods for removing whitespace from the ends of a
string. Because strings are immutable each returns a new string leaving the orig-
inal unmodified.
b. The following code uses string method strip to remove the leading and trail-
ing whitespace from sentence:
sentence.strip()
c. The following code snippets first use method lstrip to remove only leading
whitespace from sentence:
sentence.lstrip()
then use method rstrip to remove only trailing whitespace:
sentence.rstrip()
d. Methods strip, lstrip and rstrip remove only leading and/or trailing
spaces.
8.5 Changing Character Case
8.5 Q1: Which of the following statements a), b) or c) is false?
a. String methods lower and upper can convert strings to all lowercase or all up-
percase letters, respectively.
6 Chapter 8, Strings: A Deeper Look
b. Method capitalize copies the original string and returns a new string with
only the first letter capitalized (sometimes called sentence capitalization).
c. Method title copies the original string and returns a new string with only the
first character of each word capitalized (sometimes called book-title capitaliza-
tion).
d. All of the above statements are true.
8.6 Comparison Operators for Strings
8.6 Q1: Which of the following statements a), b) or c) is false?
a. Strings can be compared with the comparison operators. Recall that strings are
compared based on their underlying integer numeric values. So uppercase letters
compare as less than lowercase letters because uppercase letters have lower in-
teger values.
b. You can check character codes with ord. For example, the following code dis-
plays the values 65 and 97 for A and a, respectively:
print(f‘A: {ord(“A”)}; a: {ord(“a”)}‘)
c. In the following interactive session that compares the strings ‘Orange’ and
‘orange’, the outputs of snippets [2] and [6] (marked as ???) are False and
True:
In [1]: ‘Orange‘ == ‘orange’
Out[1]: False
In [2]: ‘Orange‘ != ‘orange’
Out[2]: ???
In [3]: ‘Orange‘ < ‘orange’
Out[3]: True
In [4]: ‘Orange‘ <= ‘orange‘
Out[4]: True
In [5]: ‘Orange‘ > ‘orange‘
Out[5]: False
In [6]: ‘Orange‘ >= ‘orange‘
Out[6]: ???
d. All of the above statements are true.
8 Chapter 8, Strings: A Deeper Look
a. Method replace takes two substrings. It searches a string for the substring in
its first argument and replaces each occurrence with the substring in its second
argument. The method returns a new string containing the results.
b. The following code replaces tab characters with commas:
values = ‘1\t2\t3\t4\t5′
values.replace(‘\t’, ‘, ‘)
c. Method replace can receive an optional third argument specifying the maxi-
mum number of replacements to perform.
d. All of the above statements are true.
8.9 Splitting and Joining Strings
8.9 Q1: Which of the following statements a), b) or c) is false?
a. When you read a sentence, your brain breaks it into individual words, or to-
kens, each of which conveys meaning.
b. Interpreters like IPython tokenize statements, breaking them into individual
components such as keywords, identifiers, operators and other elements of a pro-
gramming language.
c. Tokens typically are separated by whitespace characters such as blanks, tabs
and newlines, though other characters may be used—the separators are known
as delimiters.
d. All of the above statements are true.
8.9 Q2: Which of the following statements is false?
a. String method split with no arguments tokenizes a string by breaking it into
substrings at each whitespace character, then returns a list of tokens.
b. To tokenize a string at a custom delimiter (such as each comma-and-space
pair), specify the delimiter string (such as, ‘, ‘) that split uses to tokenize the
string, as in:
letters = ‘A, B, C, D’
letters.split(‘, ‘)
Chapter 8, Strings: A Deeper Look 9
c. If you provide an integer as split’s second argument, it specifies the maximum
number of splits. The last token is the remainder of the string after the maximum
number of splits. Assuming the string in Part (b), the code
letters.split(‘, ‘, 1)
returns
[‘A’, ‘B’, ‘C, D’]
d. There is also an rsplit method that performs the same task as split but pro-
cesses the maximum number of splits from the end of the string toward the be-
ginning.
8.9 Q3: Which of the following statements a), b) or c) is false?
a. String method partition splits a string into a tuple of three strings based on
the method’s separator argument. The three strings are the part of the original
string before the separator, the separator itself, and the part of the string after the
separator.
b. Consider a string representing a student’s name and grades:
‘Amanda: 89, 97, 92’
The following code splits the original string into the student’s name, the separator
‘: ‘ and a string representing the list of grades:
‘Amanda: 89, 97, 92’.partition(‘: ‘)
c. To search for the separator from the end of the string instead, use method
rpartition to split. For example, consider the following URL string:
url = ‘http://www.deitel.com/books/PyCDS/table_of_con-
tents.html’
The following call to rpartition splits ‘table_of_contents.html’ from the
rest of the URL:
rest_of_url, separator, document = url.rpartition(‘/’)
d. All of the above statements are true.
8.9 Q4: Which of the following statements a), b) or c) is false?
a. String method splitlines returns a list of strings representing the lines of
text split at each newline character in the original string.
b. Python stores multi-line strings with embedded \n characters to represent the
line breaks.
10 Chapter 8, Strings: A Deeper Look
c. For the string
lines = “””This is line 1
This is line2
This is line3″””
the statement
lines.splitlines(True)
keeps the newlines and returns:
[‘This is line 1’, ‘\nThis is line2′, ‘\nThis is line3′]
d. All of the above statements are true.
8.10 Characters and Character-Testing Methods
8.10 Q1: Which of the following statements a), b) or c) is false?
a. Python has separate string and character types.
b. You can use string method isdigit when validating user input that must con-
tain only digits.
c. String method isalnum returns True if the string on which you call the method
is alphanumeric—that is, it contains only digits and letters.
d. All of the above statements are true.
8.11 Raw Strings
8.11 Q1: Which of the following statements is false?
a. Backslash characters in strings introduce escape sequences—like \n for new-
line and \t for tab.
b. If you wish to include a backslash in a string, you can use two back-slash char-
acters \\.
c. Raw strings—preceded by the character r—treat each backslash as a regular
character, rather than the beginning of an escape sequence.
d. To make your code more readable, avoid using raw strings with regular expres-
sions.
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
8.12 Introduction to Regular Expressions
8.12 Q1: Which of the following statements a), b) or c) is false?
a. A regular expression string describes a search pattern for matching characters
in other strings.
b. Regular expressions can help you extract data from unstructured text, such as
social media posts.
c. Regular expressions are also important for ensuring that data is in the correct
format before you attempt to process it.
d. All of the above statements are true.
8.12 Q2: Which of the following statements is false?
a. Before working with text data, you’ll often use regular expressions to validate
the data.
b. A U.S. Social Security number contains three digits, a hyphen, two digits, a hy-
phen and four digits, and adheres to other rules about the specific numbers that
can be used in each group of digits.
c. You must create your own regular expressions to ensure that they’ll meet your
needs.
d. Many sites provide interfaces in which you can test regular expressions.
8.12 Q3: Which of the following statements a), b) or c) is false? In addition to
validating data, regular expressions often are used to:
a. Extract data from text (sometimes known as scraping)—e.g., locating all URLs
in a web page. [Though, tools like BeautifulSoup, XPath and lxml are preferred for
scraping.]
b. Clean data—for example, removing data that’s not required, removing dupli-
cate data, handling incomplete data, fixing typos, ensuring consistent data for-
mats, dealing with outliers and more.
c. Transform data into other formats—for example, reformatting data that was
collected as tab-separated or space-separated values into comma-separated val-
ues (CSV) format.
d. All of the above statements are true.
12 Chapter 8, Strings: A Deeper Look
© Copyright 2020 by Pearson Education, Inc. All Rights Reserved.
Answer: d.
8.12.1 re Module and Function fullmatch
8.12 Q4: Consider the following code that demonstrates regular expressions con-
taining literal characters—that is, characters that match themselves:
In [1]: import re
In [2]: pattern = ‘02215’
In [3]: ‘Match’ if re.fullmatch(pattern, ‘02215’) else ‘No
match’
Out[3]: ‘Match’
In [4]: ‘Match’ if re.fullmatch(pattern, ‘51220‘) else ‘No
match‘
Out[4]: ‘No match’
Which of the following statements a), b) or c) is false?
a. The re module’s fullmatch function’s first argument is the regular expression
pattern to match. Any string can be a regular expression. The variable pattern’s
value, ‘02215’, contains only literal digits that match themselves in the specified
order.
b. The second argument to fullmatch is the string that should entirely match the
pattern. If the second argument matches the pattern in the first argument, full-
match returns an object containing the matching text, which evaluates to True.
c. In snippet [4], the second argument contains the same digits as the regular
expression, but in a different order. This is still a match and fullmatch returns
an object containing the matching text, which evaluates to True.
d. All of the above statements are true.
8.12 Q5: Which of the following statements is false?
a. The regular-expression metacharacter \ begins each of the predefined regular-
expression character classes, which each match a specific set of characters.
b. The following code ensures that a string contains five consecutive digits:
re.fullmatch(r‘\d{5}’, ‘02215’)
c. A character class is a regular expression escape sequence that matches one or
more characters.
Chapter 8, Strings: A Deeper Look 13
d. The following code returns None because ‘9876’ contains only four consecu-
tive digit characters.
re.fullmatch(r‘\d{5}’, ‘9876’)
8.12 Q6: Which of the following statements is false?
a. The regular-expression quantifiers * and + are greedy—they match as many
characters as possible. The regular expression [A–Z][a–z]+ matches ‘Al’,
‘Eva’, ‘Samantha‘, ‘Benjamin’ and any other words that begin with a capital
letter followed at least one lowercase letter.
b. The ? quantifier matches zero or one occurrences of a subexpression.
c. The regular expression \d{3,} matches strings containing at least three digits.
d. You can match between n and m (exclusive) occurrences of a subexpression with
the {n,m} quantifier. The regular expression \d{3,6} matches strings contain-
ing 3 to 5 digits.
8.12.2 Replacing Substrings and Splitting Strings
8.12 Q7: Which of the following statements a), b) or c) is false?
a. By default, the re module’s sub function replaces only the first occurrence of a
pattern with the replacement text you specify. The statement
re.sub(r‘\t’, ‘, ‘, ‘1\t2\t3\t4′)
returns
‘1, 2\t3\t4′
b. The sub function receives three required arguments—the pattern to match, the
replacement text and the string to be searched and returns a new string.
c. The sub function’s keyword argument count can be used to specify the maxi-
mum number of replacements.
d. All of the above statements are true.
8.12 Q8: Which of the following statements a), b) or c) is false?
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)
Chapter 8, Strings: A Deeper Look 15
c. The re module’s finditer function works like findall, but returns a greedy
iterable of match objects.
d. For large numbers of matches, using finditer can save memory because it
returns one match at a time, whereas findall returns all the matches at once.
8.13 Intro to Data Science: Pandas, Regular Expressions
and Data Munging
8.13 Q1:Preparing data for analysis is called ________.
a. data wrangling
b. data munging
c. Both (a) and (b).
d. Neither (a) nor (b).
8.13 Q2: Assuming the following two-dimensional list:
contacts = [[‘Mike Green’, ‘demo1@deitel.com’, ‘5555555555’],
[‘Sue Brown’, ‘demo2@deitel.com’, ‘5555551234′]]
Which of the following statements a), b) or c) is false?
a. The following code creates a DataFrame from the list:
contactsdf = pd.DataFrame(contacts,
columns=[‘Name’, ‘Email’, ‘Phone’])
b. Part (a) specified column indices via the columns keyword argument but did
not specify row indices, so the rows are indexed from 0.
c. The following output shows how the DataFrame is displayed when you evalu-
ate the variable contactsdf in IPython—all column values are right aligned by
default, as they are in Python:
Name Email Phone
0 Mike Green demo1@deitel.com 5555555555
1 Sue Brown demo2@deitel.com 5555551234
d. All of the above statements are true.