Chapter 8 Review and Programming Exercises
Chapter 8 Review and Programming Exercises
8.17 Write a loop that counts the number of uppercase characters that appear in the
string referenced by the variable mystring.
8.18 Assume the following statement appears in a program:
days = 'Monday Tuesday Wednesday'
Write a statement that splits the string, creating the following list:
['Monday', 'Tuesday', 'Wednesday']
8.19 Assume the following statement appears in a program:
values = 'one$two$three$four'
Write a statement that splits the string, creating the following list:
['one', 'two', 'three', 'four']
Review Questions
Multiple Choice
1. This is the first index in a string.
a. −1
b. 1
c. 0
d. The size of the string minus one
2. This is the last index in a string.
a. 1
b. 99
c. 0
d. The size of the string minus one
3. This will happen if you try to use an index that is out of range for a string.
a. A ValueError exception will occur.
b. An IndexError exception will occur.
c. The string will be erased and the program will continue to run.
d. Nothing—the invalid index will be ignored.
4. This function returns the length of a string.
a. length
b. size
c. len
d. lengthof
5. This string method returns a copy of the string with all leading whitespace characters
removed.
a. lstrip
b. rstrip
c. remove
d. strip_leading
454 Chapter 8 More about Strings
6. This string method returns the lowest index in the string where a specified substring
is found.
a. first_index_of
b. locate
c. find
d. index_of
7. This operator determines whether one string is contained inside another string.
a. contains
b. is_in
c. ==
d. in
8. This string method returns true if a string contains only alphabetic characters and is
at least one character in length.
a. the isalpha method
b. the alpha method
c. the alphabetic method
d. the isletters method
9. This string method returns true if a string contains only numeric digits and is at least
one character in length.
a. the digit method
b. the isdigit method
c. the numeric method
d. the isnumber method
10. This string method returns a copy of the string with all leading and trailing whitespace
characters removed.
a. clean
b. strip
c. remove_whitespace
d. rstrip
True or False
1. Once a string is created, it cannot be changed.
2. You can use the for loop to iterate over the individual characters in a string.
3. The isupper method converts a string to all uppercase characters.
4. The repetition operator (*) works with strings as well as with lists.
5. When you call a string’s split method, the method divides the string into two
substrings.
Short Answer
1. What does the following code display?
mystr = 'abc'
mystr2 = '123'
mystr += mystr2
print(mystr)
review Questions 455
Algorithm Workbench
1. Assume choice references a string. The following if statement determines whether
choice is equal to ‘Y’ or ‘y’:
if choice == 'Y' or choice == 'y':
Rewrite this statement so it only makes one comparison, and does not use the or
operator. (Hint: use either the upper or lower methods.)
2. Write a loop that counts the number of space characters that appear in the string ref-
erenced by mystring.
3. Write a loop that counts the number of alphanumeric characters (letters or digits) that
appear in the string referenced by mystring.
4. Write a loop that counts the number of lowercase characters that appear in the string
referenced by mystring.
5. Write a function that accepts a string as an argument and returns true if the argument
starts with the substring 'https'. Otherwise, the function should return false.
6. Write code that makes a copy of a string with all occurrences of the lowercase letter
't' converted to uppercase.
7. Write a function that accepts a string as an argument and displays the string back-
wards.
8. Assume mystring references a string. Write a statement that uses a slicing expression
and displays the first 3 characters in the string.
9. Assume mystring references a string. Write a statement that uses a slicing expression
and displays the last 3 characters in the string.
10. Look at the following statement:
levels = 'Beginner, Average, Advanced, Expert'
Write a statement that splits this string, creating the following list:
['Beginner', 'Average', 'Advanced', 'Expert']
456 Chapter 8 More about Strings
Programming Exercises
1. Name Display
Write a program that gets strings containing a person’s first and last name as separate
values, and then displays their “initials”, “name in address book”, and “username”. For
example, if the user enters a first name of “John” and a last name of “Smith”, the program
should display “J.S.”, “John SMITH”, and “jsmith”.
2. Sum of Digits in a String
Write a program that asks the user to enter a series of single-digit numbers with nothing
separating them. The program should display the sum of all the single digit numbers in the
string. For example, if the user enters 2514, the method should return 12, which is the sum
of 2, 5, 1, and 4.
3. Date Printer
Write a program that reads a string from the user containing a date in the form mm/dd/yyyy.
It should print the date in the format March 12, 2018.
4. Morse Code Converter
Morse code is a code where each letter of the English alphabet, each digit, and various
punctuation characters are represented by a series of dots and dashes. Table 8-4 shows part
of the code.
Write a program that asks the user to enter a string, then converts that string to Morse code.
that accepts a string as an argument and returns the number of consonants that the string
contains. The application should let the user enter a string, and should display the number
of vowels and the number of consonants it contains.
10. Most Frequent Character
Write a program that lets the user enter a string and displays the character that appears most
frequently in the string.
11. Word Separator
Write a program that accepts as input a sentence in which all of the words are run together,
but the first character of each word is uppercase. Convert the sentence to a string in which
the words are separated by spaces, and only the first word starts with an uppercase letter. For
example the string “StopAndSmellTheRoses.” would be converted to “Stop and smell
the roses.”
Write one or more programs that work with this file to perform the following:
• Display the 10 most common numbers, ordered by frequency
• Display the 10 least common numbers, ordered by frequency
• Display the 10 most overdue numbers (numbers that haven’t been drawn in a long
time), ordered from most overdue to least overdue
• Display the frequency of each number 1–69, and the frequency of each Powerball
number 1–26
14. Gas Prices
In the student sample program files for this chapter, you will find a text file named
GasPrices.txt. The file contains the weekly average prices for a gallon of gas in the
United States, beginning on April 5th, 1993, and ending on August 26th, 2013. Figure 8-7
shows an example of the first few lines of the file’s contents:
Each line in the file contains the average price for a gallon of gas on a specific date. Each line
is formatted in the following way:
MM-DD-YYYY:Price
MM is the two-digit month, DD is the two-digit day, and YYYY is the four-digit year. Price is
the average price per gallon of gas on the specified date.
For this assignment, you are to write one or more programs that read the contents of the file
and perform the following calculations:
Average Price Per Year: Calculate the average price of gas per year, for each year in the file.
(The file’s data starts in April of 1993, and it ends in August 2013. Use the data that is pres-
ent for the years 1993 and 2013.)
Average Price Per Month: Calculate the average price for each month in the file.
Highest and Lowest Prices Per Year: For each year in the file, determine the date and amount
for the lowest price, and the highest price.
List of Prices, Lowest to Highest: Generate a text file that lists the dates and prices, sorted
from the lowest price to the highest.
List of Prices, Highest to lowest: Generate a text file that lists the dates and prices, sorted
from the highest price to the lowest.
You can write one program to perform all of these calculations, or you can write different
programs, one for each calculation.
15. Caesar Cipher
A “Caesar Cipher” is a simple way of encrypting a message by replacing each letter with a
letter a certain number of spaces up the alphabet. For example, if shifting the message by
13 an A would become an N, while an S would wrap around to the start of the alphabet to
become an F.
Write a program that asks the user for a message (a string) and a shift amount (an integer).
The values should be passed to a function that accepts a string and an integer as arguments,
and returns a string representing the original string encrypted by shifting the letters by the
integer. For example, a string of “BEWARE THE IDES OF MARCH” and an integer of 13
should result in a string of “ORJNER GUR VQRF BS ZNEPU”.