Practice Problems 3 Solutions

  1. [PP Problem 7.11] Using string methods, write Python expressions that produce the following (just the expression, you don’t need to write a function). You should be able to accomplish all of these tasks with just one or more string methods.

    a. "boolean".capitalize()
    b. "CO2 H2O".find("2"). Make sure to put the 2 in quotes, it’s a string, not a number.
    c.

    temp = "CO2 H2O"
    temp.find("2", temp.find("2") + 1)
    

    find can be called with a single parameter or with two parameters, where the first is a string and the second an int representing the index to start searching from. The example above starts looking for “2” at the index:

    temp.find("2")+1

    which is one after the index you found for the first occurrence.

    Another way of doing this is:

    temp.find("2", 3)

    Though this assumes that you precomputed the index of the first occurrence.

    d. 'Boolean'[0].islower()

    Gets the first character of the string and then checks to see if it is lowercase.

    e. 'MoNDaY'.lower().capitalize()

    Note that you can chain method calls.

    f. " Monday".strip()

  2. Evaluate the following expressions assuming the variable digits has the value “0123456789”, i.e. the string containing the digits 0-9.

    a. '01234'
    b. '56789'
    c. '02468'
    d. '13579'
    e. '56'

    For this kind of problem, I often find it helpful to write the indices under the characters in the string to help me more quickly determine the slice results.

  3. Write a function named last_half that takes a string as a parameter and returns the last half of that string. For odd length strings, you may round either way.

     def last_half(string):
         """
         Return the 2nd half of the string parameter
         """
         return string[len(string)//2:]
    

    Recall floor division rounds down and therefore this implementation returns a longer last half for odd length strings.

  4. Write a function named insert_noise(word) that returns a new string with the letter “a” inserted after each letter in the original string.

     def insert_noise(word):
         """
         Return the word parameter with an 'a' inserted after each letter
         """
         result = ""
         for letter in word:
             result = result + letter + "a"
         return result
    

    The result = result + ... is such a common pattern that there is a shorthand “in-place” operator, +=, that you can use instead, e.g. result += letter + "a". There are similar in-place operators for most arithmetic operations.

  5. Extend your insert_noise function from above to insert a random letter from the alphabet after each in letter in the original string.

     from random import randint
        
     ALPHABET="abcdefghijklmnopqrstuvwxyz "
    
     def insert_noise(word):
         """
         Return the word parameter with a random lower case letter inserted after each letter in word
         """
         result = ""
         for letter in word:
             result += letter + ALPHABET[randint(0, len(ALPHABET)-1)]
         return result
    

    Notice the use of len(ALPHABET) in setting the upper bound of the call to randint. This is a good practice to make sure our code works regardless of the value (and length) of ALPHABET. Also notice the we needed to subtract one from the legnth when setting the upper bound because randint has an inclusive end.

  6. As a bonus challenge, further extend your insert_noise function to only insert letters between letters in the original word. Your function should work if the original word is the empty string. As a hint, slice operations on the empty string evaluate to the empty string.

     from random import randint
            
     ALPHABET="abcdefghijklmnopqrstuvwxyz "
        
     def insert_noise3(word):
         """
         Return the word parameter with a random lower case letter inserted between each letter in word
         """
         result = ""
         for letter in word:
             result = result + letter + ALPHABET[randint(0, len(ALPHABET)-1)]
         return result[:-1]
    

    We can use slicing to remove the last character that we appended by slicing up to but not including the last character (indicated by the negative indexing). Slicing has the nice behavior that performing slice operations on an empty string just evaluates to an empty string (and not an error).