Here are some exercises for you to try on your own. Solutions are available at http://pragprog.com/titles/gwpy3/practical-programming.
In the Python shell, execute the following method calls:
Using string method count, write an expression that produces the number of o’s in ’tomato’.
Using string method find, write an expression that produces the index of the first occurrence of o in ’tomato’.
Using string method find, write a single expression that produces the index of the second occurrence of o in ’tomato’. Hint: Call find twice.
Using your expression from the previous exercise, find the second o in ’avocado’. If you don’t get the result you expect, revise the expression and try again.
Using string method replace, write an expression that produces a string based on ’runner’ with the n’s replaced by b’s.
Variable s refers to ’ yes ’. When a string method is called with s as its argument, the string ’yes’ is produced. Which string method was called?
Variable fruit refers to ’pineapple’. For the following function calls, in what order are the subexpressions evaluated?
Variable season refers to ’summer’. Using string method format and variable season, write an expression that produces ’I love summer!’
Variables side1, side2, and side3 refer to 3, 4, and 5, respectively. Using string method format and those three variables, write an expression that produces ’The sides have lengths 3, 4, and 5.’
Using string methods, write expressions that produce the following:
Complete the examples in the docstring and then write the body of the following function:
| def total_occurrences(s1: str, s2: str, ch: str) -> int: |
| """Precondition: len(ch) == 1 |
| |
| Return the total number of times that ch occurs in s1 and s2. |
| |
| >>> total_occurrences('color', 'yellow', 'l') |
| 3 |
| >>> total_occurrences('red', 'blue', 'l') |
| |
| >>> total_occurrences('green', 'purple', 'b') |
| |
| """ |