Exercises for Lesson 4
Exercise 1: Playing around with strings
For this exercise, we’ll use the following statements:
s1 = "apple"
s2 = "banana!"
Exercise 1a: from expression to output
Predict the result of evaluating each of the following string expressions.
a) "I would like a " + s2
b) 3 * s1 + s2
c) s2[2:4]
d) s1[3] + s2[3:] + s2[-1]
e) "-".join(s2.split("n"))
Exercise 1b: from output to expression
Build a Python expression that could construct each of the following results by performing string operations on s1
and s2
.
s1 = "apple"
s2 = "banana!"
a) "nana"
b) "apple banana! apple banana! apple banana!"
c) ["b", "n", "n", "!"]
Exercise 2: Looping through strings
Show the output that would be generated by each of the following program fragments:
a) for ch in "banana":
print(ch)
b) for word in "apple banana cat dog elephant...".split():
print(word)
c) for s in "apple".split("p"):
print(s)
d) msg = "" # accumulate a string in msg
for s in "apple banana cat".split("a"):
msg = msg + s
print(msg)
Exercise 3: Acronym-ification
An acronym is a word formed by taking the first letters of the words in a phrase and making a word from them. For example, RAM is an acronym for “random access memory”.
Write a program that allows the user to type in a phrase and then outputs the acronym for that phrase. The acronym should be all uppercase, even if the words in the phrase are not capitalized.
Hint: You should use the accumulator pattern to build up the resulting string.
Exercise 4: Word statistics
Write a program that asks the user to type in a sentence, and outputs the number of words in that sentence.
Here is an example interaction:
Please enter a sentence: Apple banana cat dog elephant fish giraffe.
That sentence has 7 words.
Exercise 5: Looping through strings, part 2
Show the output that would be generated by the following program fragment:
msg = ""
for ch in "banana":
msg = msg + chr(ord(ch) + 1)
print(msg)