Книга: Practical Programming, Fourth Edition
Назад: A Methodical Review
Дальше: Chapter 8: Storing Collections of Data Using Lists

Exercises

Here are some exercises for you to try on your own.

  1. In the Python shell, execute the following method calls:

    1. ’hello’.upper()
    2. ’Happy Birthday!’.lower()
    3. ’WeeeEEEEeeeEEEEeee’.swapcase()
    4. ’ABC123’.isupper()
    5. ’aeiouAEIOU’.count(’a’)
    6. ’hello’.endswith(’o’)
    7. ’hello’.startswith(’H’)
  2. Using string method count, write an expression that produces the number of o’s in ’tomato’.

  3. Using string method find, write an expression that produces the index of the first occurrence of o in ’tomato’.

  4. Using string method find, write a single expression that produces the index of the second occurrence of o in ’tomato’. Hint: Call find twice.

  5. 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.

  6. Using string method replace, write an expression that produces a string based on ’runner’ with the n’s replaced by b’s.

  7. 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?

  8. Variable fruit refers to ’pineapple’. For the following function calls, in what order are the subexpressions evaluated?

    1. fruit.find(’p’, fruit.count(’p’))
    2. fruit.count(fruit.upper().swapcase())
    3. fruit.replace(fruit.swapcase(), fruit.lower())
  9. Using string methods, write expressions that produce the following:

    1. A copy of ’boolean’ capitalized
    2. The first occurrence of ’2’ in ’CO2 H2O’
    3. The second occurrence of ’2’ in ’CO2 H2O’
    4. True if and only if ’Boolean’ begins lowercase
    5. A copy of "MoNDaY" converted to lowercase and then capitalized
    6. A copy of "   Monday" with the leading whitespace removed
  10. 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:
     """Return the total number of times that ch occurs in s1 and s2.
     
      Precondition: len(ch) == 1
     
      >>> total_occurrences('color', 'yellow', 'l')
      3
      >>> total_occurrences('red', 'blue', 'l')
     
      >>> total_occurrences('green', 'purple', 'b')
     
      """
Назад: A Methodical Review
Дальше: Chapter 8: Storing Collections of Data Using Lists