Exercises for Lesson 4
Exercise 1: Looping through strings
Show the output that would be generated by each of the following program fragments:
a) for ch in "zebra":
print(ch)
b) for ch in "fish":
print("#" + ch * 3 + " " + ch)
Exercise 2: Looping through strings, part 2
Show the output that would be generated by the following program fragment:
msg = ""
for ch in "aprilfools":
msg = msg + chr(ord(ch) + 1)
print(msg)
Exercise 3: Playing around with strings
For this exercise, we’ll use the following statements:
s1 = "apple"
s2 = "banana!"
Exercise 3a: from expression to output
Predict the result of evaluating each of the following string expressions.
a) "I would like a " + s2
b) 2 * s1 + s2
c) s2[2:4]
d) s1[0] + s2[-2:] + s2[-1]
e) s2[len(s1)]
Exercise 3b: 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!"